SpringBoot定时任务


注解方式和接口方式,是可以在一个项目中共存的。

基于注解的方式

  1. 在启动类上,开启定时任务功能(加上@EnableScheduling注解):
@EnableScheduling
@SpringBootApplication
@ComponentScan({ "com.boco.fyk.timer.**" })
public class TimerApplication {
	public static void main(String[] args) {
		SpringApplication.run(TimerApplication.class, args);
	}
}
  1. 编写定时任务类:
@Component
@Slf4j
public class Test {

	@Async
	@Scheduled(fixedDelay = 10000)
	public void handle() {
		log.info("fixedDelay-每间隔多少毫秒执行一次(这个时间间隔是:最后一次调用结束和下一次调用开始之间)!");
	}
	
	@Async
	@Scheduled(fixedRate = 10000)
	public void handle2() {
		log.info("fixedRate-每间隔多少毫秒执行一次!");
	}
	
	@Async
	@Scheduled(cron = "0/10 * * * * *")
	public void handle3() {
		log.info("cron-cron表达式配置执行时间,不支持年");
	}
}

需要注意的是,定时任务默认是以单线程来执行的。所以,可能出现一个问题,就是定时任务在执行的过程中,发生了异常,那么定时任务就不会再执行了。因此,这里要使用多线程来执行这个定时任务。
这里:

  • @Component:表示要将这个类,交由spring管理;
  • @Async:表示开启多线程来执行方法;(SpringBoot中多线程的使用,见:异步任务(多线程)
  • @Scheduled:定时任务的时间配置;

基于接口的方式

基于注解的方式很简单,但是也存在一个问题,那就是执行周期的时间,无法动态改变。也就是说,要调整执行周期,只有重启任务。
要实现动态改变执行周期,可以使用接口的方式:

  1. 同注解方式一样,先要开启定时任务:
@EnableScheduling
@SpringBootApplication
@ComponentScan({ "com.boco.fyk.timer.**" })
public class TimerApplication {
	public static void main(String[] args) {
		SpringApplication.run(TimerApplication.class, args);
	}
}
  1. 实现接口:
@Component
@Slf4j
public class DynamicScheduleTask implements SchedulingConfigurer {

	/**
	 * 执行定时任务.
	 */
	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.addTriggerTask(() -> (new CustomTask()).doThings(),
				triggerContext -> new CronTrigger("0/10 * * * * *").nextExecutionTime(triggerContext));
	}

	class CustomTask {
		public void doThings() {
			log.info("执行了一个自定义定时任务");
		}
	}
}

这里,作为示例,是把时间写死了,实际情况,可以从数据库或其他地方获取。
另外new CronTrigger(“0/10 * * * * *”).nextExecutionTime(triggerContext))代码,会在每次定时任务都会重新执行这个代码,所以,这里可以换成其他语句,获取到具体的定时任务值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值