@Component
/*@EnableScheduling*/ //开启定时任务,可以写在类上或springboot启动器上
public class TaskDemo {
/**
*
* 每分钟执行一次
*/
@Scheduled(cron = "0 0/1 * * * ?")
public void work() throws Exception {
System.out.println("每分钟执行一个的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0/2 * * * * ?") //每2秒执行一次
public void doSomething() throws Exception {
System.out.println("每2秒执行一个的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0 0 0/1 * * ? ") // 每一小时执行一次
public void goWork() throws Exception {
System.out.println("每一小时执行一次的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0 0 10,14,16 * * ? ") // 每天上午10点,下午2点,4点
public void goWork2() throws Exception {
System.out.println("每天上午10点,下午2点,4点执行一次的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0 0/30 9-17 * * ? ") // 朝九晚五工作时间内每半小时
public void goWork3() throws Exception {
System.out.println("朝九晚五工作时间内每半小时执行一次的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0 15 10 * * ? ") // 每天上午10:15触发
public void goWork4() throws Exception {
System.out.println("每天上午10:15触发执行一次的定时任务:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
注解的方式定时任务
最新推荐文章于 2022-03-21 16:17:34 发布