方式一:@Scheduled注解
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @author qinchunlin
* @version 1.0.0
* @ClassName SaticScheduleTask
* @Description
* @createTime 2021年02月24日 13:20:00
*/
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SaticScheduleTask {
@Scheduled(cron = "0/5 * * * * ?") //3.添加定时任务
//@Scheduled(fixedRate=5000) //或直接指定时间间隔,例如:5秒
private void configureTasks() {
System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
}
}
方式二:TimerTask
import java.util.Timer;
import java.util.TimerTask;
/**
* TODO 使用 TimerTask 创建job定时任务
*
* @author 王松
* @date 2019/9/14 0014 20:50
*/
public class JobTimerTask {
static long count = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
count++;
System.out.println(count);
}
};
//创建timer对象设置间隔时间
Timer timer = new Timer();
// 间隔天数
long delay = 0;
// 间隔毫秒数
long period = 1000;
timer.scheduleAtFixedRate(timerTask, delay, period);
}
}