In Java, you can use the java.util.Timer
or java.util.concurrent.ScheduledExecutorService
classes to implement scheduled tasks.
The following is a sample code usingjava.util.Timer
to implement scheduled tasks:
public class MyTimerTask extends TimerTask {
@Override
public void run() {
// 定时任务代码
System.out.println("定时任务执行了1111111111"+new Date());
}
public static void main(String[] args) {
Timer timer = new Timer();
// 每隔5秒执行一次定时任务
timer.schedule(new MyTimerTask(), 0, 1000);
}
}
The above code creates a class inherited from TimerTask
, overrides the method, and writes in it The code for the scheduled task. In the method, an object is created, and the method is used to schedule the execution of the scheduled task. This method accepts two parameters: the scheduled task object to be executed and the delay time (in milliseconds). In this example, the scheduled task will be executed after a delay of 5 seconds. MyTimerTask
run()
main()
Timer
schedule()
The following is a sample code usingjava.util.concurrent.ScheduledExecutorService
to implement scheduled tasks:
public class MyScheduledTask implements Runnable {
@Override
public void run() {
// 定时任务代码
System.out.println("定时任务执行了" +new Date());
}
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 每隔5秒执行一次定时任务
executor.scheduleAtFixedRate(new MyScheduledTask(), 0, 1, TimeUnit.SECONDS);
}
}
The above code creates a class that implements the Runnable
interface and overrides the method, in which Wrote the code for scheduled tasks. In the method, an object is created, and the method is used to schedule the execution of the scheduled task. This method accepts three parameters: the scheduled task object to be executed, the delay time and the time unit. In this example, the scheduled task will be executed after a delay of 5 seconds. MyScheduledTask
run()
main()
ScheduledExecutorService
scheduleAtFixedRate()