@Scheduled 定时任务总结

@Scheduled

作用:spring定时器(定时执行一次或定时轮询执行一段代码)

使用场景:注解在方法上

参数说明:常用参数

@Scheduled 参数说明

String cron:cron表达式定义了方法执行的时间规则(网上对这个的说明很多就不墨迹了)

生成器工具地址-http://cron.qqe2.com/

Long fixedDelay:定时任务每隔多久执行一次,单位是毫秒,上一次任务结束后开始计算下次执行的时间。

例子:@Scheduled(fixedDelay = 1000 * 10) //10秒发送一次

······················scheduled1开始执行·······················2018-07-27 14:00:00

······················scheduled1结束执行·······················2018-07-27 14:00:05

······················scheduled2开始执行·······················2018-07-27 14:00:15

······················scheduled2结束执行·······················2018-07-27 14:00:20

······················scheduled3开始执行·······················2018-07-27 14:00:30

······················scheduled3结束执行·······················2018-07-27 14:00:35

 

Long fixedRate:与fixedDelay一样表示定时任务的执行时间间隔,不同的是fixedRate的不会受到上一次任务结束时间的影响

例子:@Scheduled(fixedRate = 1000 * 10) //10秒发送一次

······················scheduled1开始执行·······················2018-07-27 14:00:00

······················scheduled1结束执行·······················2018-07-27 14:00:05

······················scheduled2开始执行·······················2018-07-27 14:00:10

······················scheduled2结束执行·······················2018-07-27 14:00:15

······················scheduled3开始执行·······················2018-07-27 14:00:20

······················scheduled3结束执行·······················2018-07-27 14:00:25

 

Long initialDelay:项目启动后不马上执行定时器,根据initialDelay的值延时执行。

 

注意事项:

1.定时器的参数有两种写法是用cron表达式,或者使用fixedDelay、fixedRate等参数直接配置

需要注意的是 使用cron表达式的方法,在项目首次启动后不会直接运行,而是等到执行周期才会执行

而使用第二种方式的定时器方法,在项目启动成功后会马上开始执行一次,再按照时间周期执行。

测试说明:

使用第一种配置方式,项目启动后方法不会执行,而是等到执行周期到了才会执行方法

使用第二种参数方式的方法,项目启动成功后马上执行了一次

2.定时器默认为单线程,所以如果项目中使用多个定时器要配置线程池 

注意这里的@EnableScheduling,使用它来开启定时器注解

@Configuration
@EnableScheduling
public class SchedulingConfig implements SchedulingConfigurer {

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.setScheduler(taskExecutor());
	}

	@Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(5 ,new ThreadFactory() {
        	private final AtomicLong counter = new AtomicLong();
			
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = new Thread(r);
				thread.setName("test-scheduler-" + counter.incrementAndGet());
				return thread;
			}
			
		});
    }
	
}

 

  • 20
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值