1、Timer
JDK自带的Timer API算是最古老的定时任务实现方式了。Timer是一种定时器工具,使用java.util.Timer工具类。用来在一个后台线程计划执行指定任务。它可以安排任务“执行一次”或者定期“执行多次”。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Timer是JAVA自带的定时任务类;优点:使用方便
*/
public class MyTimerTask {
public static void main(String[] args) {
// 定义一个定时任务
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String dateStr = sdf.format(new Date());
System.out.println("运行定时任务:" + dateStr);
}
};
// 计时器
Timer timer = new Timer();
// 添加执行任务(延迟 1s 执行,每 3s 执行一次)
timer.schedule(timerTask, 1000, 3000);
}
}
2、基于@Scheduled注解
2.1、SpringBoot启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(value = "com.example.schedule.schedule")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.2、实现示例
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @Description:
* @Author: yangyongbing
* @CreateTime: 2023/07/27 16:58
* @Version: 1.0
*/
@EnableScheduling
@Configuration
public class ScheduleTask {
@Scheduled(cron = "0/5 * * * * ?")
private void taskOne(){
System.out.println("------------------------------------------*********************taskOne***************************------------------------------------------------------------");
}
@Scheduled(cron = "0/3 * * * * ?")
private void taskTwo(){
System.out.println("------------------------------------------*********************taskTwo***************************------------------------------------------------------------");
}
}
注解含义:
* @Scheduled(cron = "0/5 * * * * ?") //每隔5s执行一次
* @Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
* @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行
* @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
* @Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次