When a system is just built, it often needs to be executed regularly, but if it doesn’t, some people recommend 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);
}
}
Or 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);
Both of them can run on a single machine without any problems, but if there are multiple machines, they cannot be used because of repeated execution.
The convenience of the solution can be to use locks (database or redis, etc.), which will increase the complexity of the program. Here is a better solution: use the crontab that comes with linux
1. Use crontab
crontab -u //Set a user's cron service
crontab -l //List the details of
a user's cron service
crontab -r //Delete a user's cron service crontab -e //Edit a user's cron service
2. cron expression
Basic format:
-
-
-
-
- command Time-sharing day, month and week
. The first column of the command indicates the minutes from 1 to 59. Use each minute or /1 to indicate the frequency
- command Time-sharing day, month and week
-
-
-
The second column indicates hours 1 to 23 (0 means 0 o'clock)
The third column indicates dates 1~31
The fourth column indicates the month 1-12,
the fifth column identification number week 0-6 (0 means Sunday)
Command to be run in column 6