SpringBoot 定时任务

三种

  • 一般常用的定时任务
  • 多线程异步
  • 基于接口,查询数据库,实时生效

一般常用的定时任务 及 多线程异步使用定时任务

不加@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("基于接口实现定时任务实时生效~~");
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容