免费网站建设平台哪个好,广州沙河一起做网站的网址,易搜网站建设,wordpress中动态设置轮播图片Cron表达式生成器
基于接口的方式 使用Scheduled 注解很方便#xff0c;但缺点是当我们调整了执行周期的时候#xff0c;需要重启应用才能生效#xff0c;这多少有些不方便。为了达到实时生效的效果#xff0c;那么可以使用接口来完成定时任务#xff0c;统一将定时器信…Cron表达式生成器
基于接口的方式 使用Scheduled 注解很方便但缺点是当我们调整了执行周期的时候需要重启应用才能生效这多少有些不方便。为了达到实时生效的效果那么可以使用接口来完成定时任务统一将定时器信息存放在数据库中。
1. 在mysql中执行一下脚本插入定时任务
drop table if exists scheduled;
create table scheduled (cron_id varchar(30) NOT NULL primary key,cron_name varchar(30) NULL,cron varchar(30) NOT NULL
);
insert into scheduled values (1,定时器任务一,0/6 * * * * ?);
2. Mapper层
Repository
Mapper
public interface CronMapper {Select(select cron from scheduled where cron_id #{id})public String getCron(int id);
}
3. task类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;/*** Description* ClassName MyTask* Author User* date 2020.06.07 15:23*/
Component
EnableScheduling
public class MyTask implements SchedulingConfigurer {Autowiredprotected CronMapper cronMapper;Overridepublic void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.addTriggerTask(() - process(),triggerContext - {String cron cronMapper.getCron(1);if (cron.isEmpty()) {System.out.println(cron is null);}return new CronTrigger(cron).nextExecutionTime(triggerContext);});}private void process() {System.out.println(这里实现定时任务具体操作);}
}