欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Springboot 不同定时任务实现及场景

Springboot 不同定时任务实现及场景

2024/10/24 9:30:10 来源:https://blog.csdn.net/qq_32719215/article/details/140474576  浏览:    关键词:Springboot 不同定时任务实现及场景

实现1、通过开启@EnableScheduling 及注解@Scheduled 实现定时执行任务

【完整示例】

package org.javatrip.springboottimer;import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.util.Date;@Component
@EnableScheduling
public class ScheduledTasks {//   @Scheduled(cron = "*/50 * * * * ?") // 每小时执行一次@Scheduled(fixedRate = 50000, initialDelay = 5000,fixedDelay = 5000)public void executeEveryHour() {System.out.println("定时器被触发: " + new Date());}
}

有两种方式为不同场景

  • 配置Cron表达式,@Scheduled(cron = “* */50 * * * ?”)

建议:直接点击在线Cron表达式生成器生成参数比较方便:https://www.matools.com/cron/
**【注意】**Cron表达式的开始执行时机,为表达式对应的,系统执行时间所对应的cron表达式时间,
如:每5分钟执行一次,当前系统时间为 10:03分,则定时器开始执行为 10:05执行

  • 固定频率执行@Scheduled(fixedRate = 50000, initialDelay = 5000,fixedDelay = 5000)
    该方式可以设置在系统启动后立即执行,也可延迟执行

实现2、通过开启@EnableScheduling及实现接口 SchedulingConfigurer 完成定时执行任务

完整示例

package org.javatrip.springboottimer;import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;@EnableScheduling
@Configuration
public class QuartzSchedulerTask implements SchedulingConfigurer {@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {// 设置可变定时器String cors = "0/"+getCount()+" * * * * ?";// 注册方式1taskRegistrar.addCronTask(() -> {System.out.println("SchedulingConfigurer cron task");}, cors);// 注册方式2taskRegistrar.addCronTask(new Runnable() {@Overridepublic void run() {System.out.println("SchedulingConfigurer cron task");}}, cors);}private int getCount() {int randomNumber = (int)(Math.random() * 10) + 1;return randomNumber;}
}

这场景主要可以实现 可变定时任务
【注意】 cors可以通过动态修改方式达到触发定时任务的可变时间。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com