Cron表達式生成器
基于接口的方式?
?? 使用@Scheduled 注解很方便,但缺點是當我們調整了執(zhí)行周期的時候,需要重啟應用才能生效,這多少有些不方便。為了達到實時生效的效果,那么可以使用接口來完成定時任務,統(tǒng)一將定時器信息存放在數(shù)據(jù)庫中。
1.?在mysql中執(zhí)行一下腳本插入定時任務:
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層文章來源:http://www.zghlxwxcb.cn/news/detail-689709.html
@Repository
@Mapper
public interface CronMapper {
@Select("select cron from scheduled where cron_id = #{id}")
public String getCron(int id);
}
3.?task類:文章來源地址http://www.zghlxwxcb.cn/news/detail-689709.html
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 {
@Autowired
protected CronMapper cronMapper;
@Override
public 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("這里實現(xiàn)定時任務具體操作");
}
}
到了這里,關于Spring boot開啟定時任務的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!