您的位置:首页 > 博客中心 > 网络系统 >

定时任务选型,你也许有更好的选择?-linux定时任务crontab

时间:2022-04-03 16:18

技术图片
一个系统刚刚构建的时候,往往需要定时执行的任务,但没有,有人就推荐java的timer

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest extends TimerTask {

private String jobName = "";

public TimerTest(String jobName) {
super();
this.jobName = jobName;
}

@Override
public void run() {
System.out.println("execute " + jobName);
}

public static void main(String[] args) {
Timer timer = new Timer();
long delay1 = 1 * 1000;
long period1 = 1000;
// 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 job1
timer.schedule(new TimerTest("job1"), delay1, period1);
long delay2 = 2 * 1000;
long period2 = 2000;
// 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 job2
timer.schedule(new TimerTest("job2"), delay2, period2);
}
}

或者sheduler,

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest implements Runnable {
 private String jobName = "";

 public ScheduledExecutorTest(String jobName) {
 super();
 this.jobName = jobName;
 }

 @Override
 public void run() {
 System.out.println("execute " + jobName);
 }

 public static void main(String[] args) {
 ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

 long initialDelay1 = 1;
 long period1 = 1;
 // 从现在开始1秒钟之后,每隔1秒钟执行一次job1
 service.scheduleAtFixedRate(
 new ScheduledExecutorTest("job1"), initialDelay1,
 period1, TimeUnit.SECONDS);

 long initialDelay2 = 1;
 long delay2 = 1;
 // 从现在开始2秒钟之后,每隔2秒钟执行一次job2
 service.scheduleWithFixedDelay(
 new ScheduledExecutorTest("job2"), initialDelay2,
 delay2, TimeUnit.SECONDS);

这两样在单机上运行都没有问题,但如果有多台机器就无法使用了,原因是重复执行。

解决的方便可以使用锁(数据库或者redis等其他的),这样会增加程序的复杂度,这里有一个更好的解决方式:使用linux自带的crontab

1.使用crontab

crontab -u //设定某个用户的cron服务
crontab -l //列出某个用户cron服务的详细内容
crontab -r //删除某个用户的cron服务
crontab -e //编辑某个用户的cron服务

2. cron表达式

基本格式 :

          • command 分 时 日 月 周 命令
            第1列表示分钟1~59 每分钟用或者 /1表示频率

第2列表示小时1~23(0表示0点)

第3列表示日期1~31

第4列表示月份1~12
第5列标识号星期0~6(0表示星期天)

第6列要运行的命令

3.保存

本类排行

今日推荐

热门手游