springboot 定时任务(写完类以后启动)

1

 

2

3

package com.example.hostel.controller;

import java.time.LocalDateTime;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.Controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
@Controller
@EnableScheduling
@Configuration
public class DynamicSchedule implements SchedulingConfigurer {
  
    //动态获取数据映射的信息
    @Mapper
    public interface CronMapper{
        @Select("select cron from schedule")
        public String getCron();
    }
    
    //注入mapper
    @Autowired
    CronMapper cronMapper;
    
    //执行定时任务
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
      
         taskRegistrar.addTriggerTask(
                    //1.添加任务内容(Runnable)
                    () -> System.out.println("执行动态定时任务: " + LocalDateTime.now()),
                    //2.设置执行周期(Trigger)
                    triggerContext -> {
                        //2.1 从数据库获取执行周期
                        String cron = cronMapper.getCron();
                        //2.2 合法性校验.
                        if (StringUtils.isEmpty(cron)) {
                            // Omitted Code ..s
                        }
                        //2.3 返回执行周期(Date)
                        return new CronTrigger(cron).nextExecutionTime(triggerContext);
                    }
            );
    }

}
 

package com.example.hostel.controller;

import java.time.LocalDate;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
//用于配置类,兼备componnet的效果
@Configuration
//开启定时任务
@EnableScheduling
//定时任务
@Controller
public class Scheduled {
     //添加定时任务 
    @org.springframework.scheduling.annotation.Scheduled(cron="0/10 * * * * ?")
    /*Cron表达式参数分别表示:
    秒(0~59) 例如0/5表示每5秒
    分(0~59)
    时(0~23)
    日(0~31)的某天,需计算
    月(0~11)
    周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)*/
    //直接指定时间  这里是10秒
    //@org.springframework.scheduling.annotation.Scheduled(fixedRate=10000)

    private void shceduleTest() {
        System.out.println("正在执行定时任务"+LocalDate.now());
        
    }

}
 

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值