三种
- 一般常用的定时任务
- 多线程异步
- 基于接口,查询数据库,实时生效
一般常用的定时任务 及 多线程异步使用定时任务
不加@EnableAsync 和 @Async 就是正常的定时任务
1.在启动类中用注解@EnableScheduling进行标注,表明此模块中存在定时任务;加@EnableAsync表明开启多线程异步执行
2.在定时任务类上加@Component 注解,注入容器
3.在方法上加注解@Scheduled(cron=" */6 * * * * ?")设置执行周期 和@Async开启多线程异步执行
其中可以加initialDelay可设置容器启动后延时执行;
@Component
@EnableScheduling //开启定时任务
public class ScheduleTask {
//容器启动后,延迟10秒后再执行一次定时器,以后每10秒再执行一次该定时器。
@Scheduled(initialDelay = 10000, fixedRate = 10000)
@Async
private void myTasks3() {
System.out.println("定时任务~~~");
}
基于接口的方式 查询数据库,修改定时任务周期,实现实时生效
1.数据库建表
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. 写定时任务代码,修改数据库中数据即可实现实时生效
@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("基于接口实现定时任务实时生效~~");
}
}