使用Spring @Scheduled标签可以很简单地定义Scheduled Task,但是有时我们需要在程序里动态地改写Cron的配置。
什么时候呢?
额,比如:
老板觉得Cron配置太难看了,想直接这样:10:15
两个标签: @EnableScheduling
, @Scheduled
@SpringBootApplication @EnableScheduling public class SchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SchedulingTasksApplication.class); } }
public class ScheduleTaskSimpleJob { @Scheduled(cron = "0 15 10 * * ?") public void scheduleCronTask() { long now = System.currentTimeMillis() / 1000; System.out.println( "schedule tasks using cron jobs - " + now); } }
Implements SchedulingConfigurer
就可以,想怎么改怎么改。
public class ScheduleTaskSimpleJob implements SchedulingConfigurer { public void scheduleCronTask() { long now = System.currentTimeMillis() / 1000; System.out.println( "schedule tasks using cron jobs - " + now); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { scheduleCronTask(); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { //TODO 将时间配置10:15转换为cron String cron = "0 15 10 * * ?"; CronTrigger trigger = new CronTrigger(cron); Date nextExecDate = trigger.nextExecutionTime(triggerContext); return nextExecDate; } }); } }
热门文章
- Celery ETA任务重复提交的问题解决
- 「1月22日」最高速度21.5M/S,2025年Nekoray每天更新免费节点订阅链接
- 云原生之Docker实战使用docker部署Jellyfin个人影音服务器
- 动物疫苗接种注意问题及措施(动物疫苗使用时的注意事项有哪些)
- 动物免疫接种意义(免疫接种在动物疫病防治上的意义)
- EFCore 6.0入门看这篇就够了
- 「2月20日」最高速度22.5M/S,2025年Nekoray每天更新免费节点订阅链接
- 合肥宠物领养网站有哪些(合肥宠物领养中心)
- 宠物店的宠物从哪进货便宜(宠物店都是在哪里进货)
- 「1月16日」最高速度20M/S,2025年Nekoray每天更新免费节点订阅链接