可配置的定时任务(只修改小时)

通过读取数据库,配置定时任务
1.controller

@Slf4j
@RestController
@RequestMapping(value = "/yfgs/cron")
@Api(description = "定时任务corn")
public class CornController {

    @Autowired
    public CornService cornService;

    @ApiOperation(value = "查询当前正在使用corn")
    @RequestMapping(value = "/findCorn", method = RequestMethod.GET)
    public CronVo findCorn() {

        return cornService.getTime();
    }

    @ApiOperation(value = "编辑当前正在使用corn")
    @RequestMapping(value = "/editCorn", method = RequestMethod.POST)
    public Json<CronVo> editCorn(@Validated @RequestBody CronVo time, BindingResult result) {

        Json<CronVo> timeJson = new Json<>();
        if (result.hasErrors()) {
            timeJson.setCode(400);
            timeJson.setSuccess(false);
            timeJson.setError("【hours只能传整数0~23或者*】");
            return timeJson;
        }
        cornService.editCorn(time);
        timeJson.setCode(200);
        timeJson.setSuccess(true);
        return timeJson;
    }

}

2.实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Cron implements Serializable {
    private Integer cron_id;

    @Pattern(regexp = "^([0-9]|[1-5][0-9]|59|[/*]|[0-9]/[1-5][0-9]|[1-5][0-9]/[1-5][0-9])|[0-9]/[0-9]$",
            message = "seconds参数不正确")
    private String seconds;

    @Pattern(regexp = "^([0-9]|[1-5][0-9]|59|[/*]|[0-9]/[1-5][0-9]|[1-5][0-9]/[1-5][0-9])|[0-9]/[0-9]$",
            message = "minutes参数不正确")
    private String minutes;

    @Pattern(regexp = "([0-9]|[1-2][0-3]|[/*])",
            message = "hours只能传整数0~23或者*")
    private String hours;

    @Pattern(regexp = "^([1-9]|[1-2][2-9]|[1-3][0-1]|[/*]|[0-9]/[1-9]|[0-9]/([1-2][2-9])|[0-9]/([1-3][0-1]))$",
            message = "dayofMonth参数不正确")
    private String dayofMonth;

    @Pattern(regexp = "^([1-7]|[/*]|[0-7]/[1-7])$",
            message = "dayofWeek参数不正确")
    private String dayofWeek;

    @Pattern(regexp = "^([1-9]|[1][0-2]|)$",
            message = "month参数不正确")
    private String month;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CronVo {
    @Pattern(regexp = "^([0-9]|[1-2][0-3]|[/*])$",
            message = "hours只能传整数0~23或者*")
    private String hours;
}

3.dao层

@Repository
public interface CronMapper {
    //@Select("select cron from cron limit 1")
    //String getCron();
    @Select("select cron_id,seconds,minutes,hours,dayofMonth,month,dayofWeek from cron limit 1")
    Cron getCron();

    @Select("select hours from cron limit 1")
    CronVo getTime();

    @Update("update cron set seconds= #{cron.seconds}," +
            " minutes= #{cron.minutes}," +
            "hours= #{cron.hours}," +
            "dayofMonth= #{cron.dayofMonth}," +
            "month= #{cron.month}," +
            "dayofWeek= #{cron.dayofWeek}" +
            " where cron_id=#{cron_id}")
    void editCorn(@Param("cron") Cron cron, @Param("cron_id") Integer id);

    @Insert({"insert into cron ( cron_id,seconds, minutes, hours, dayofMonth,month,dayofWeek) " +
            "values(#{cron.cron_id}, #{cron.seconds}, #{cron.minutes}, #{cron.hours}, #{cron.dayofMonth},#{cron.month},#{cron.dayofWeek})"})
    void addCron(@Param("cron") Cron cron);
}

4.service

@Service
public class CornServiceImpl implements CornService {
    @Autowired
    private CronMapper cronMapper;

    @Override
    public Cron findCorn() {
        return cronMapper.getCron();
    }

    @Override
    public CronVo getTime() {
        CronVo time = cronMapper.getTime();
        String s = time.getHours();
        CronVo timeStr = new CronVo();
        if (s.contains("*")) {
          return time;
        } else {
            String[] split = s.split("/");
            String hours = split[1];
            timeStr.setHours(hours);
        }
        return timeStr;
    }

    @Override
    public void editCorn(CronVo time) {

        //获取当前时间的整点数
        Date today = new Date();
        SimpleDateFormat f = new SimpleDateFormat("HH");
        String CurrentHour = f.format(today);
        Cron cron = new Cron();
        cron.setCron_id(1);
        cron.setSeconds("0");
        cron.setMinutes("0");
        cron.setDayofWeek("*");
        cron.setDayofMonth("*");
        cron.setMonth("*");
        if (time.getHours().toString().contains("*")) {
            cron.setHours("*");
        } else {
            cron.setHours(CurrentHour + "/" + time.getHours());
        }

        Integer id = cron.getCron_id();
        cronMapper.editCorn(cron, id);

    }

}
public interface CornService {
    Cron findCorn();

    CronVo getTime();

    void editCorn(CronVo time);

}

5.定时任务

/**
 * 动态修改cron
 */
@Component
public class Task implements SchedulingConfigurer {
    private static Logger log = LoggerFactory.getLogger(Task.class);


    private static String cron;
    @Autowired
    @SuppressWarnings("all")
    CronMapper cronMapper;

    @Autowired
    private JiraDataScheduler jiraDataScheduler;
    @Autowired
    private SonarDataScheduler sonarDataScheduler;


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        scheduledTaskRegistrar.addTriggerTask(doTask1(), getTrigger());

    }
    //同时被定时调度器开启俩个线程
    private Runnable doTask1() {
        return new Runnable() {
            @Override
            public void run() {
                new MyThread().start();
                new Thread(doTask()).start();
            }
        };
    }
    //sonarDataScheduler的线程
    public class MyThread extends Thread {
        @Override
        public void run() {
            log.info("sonarDataScheduler开始执行,时间为:" + new SimpleDateFormat("yyyy-MM-dd: HH:mm:ss").format(new Date(System.currentTimeMillis())));
            sonarDataScheduler.getSonarData();
            log.info("sonarDataScheduler执行完毕,时间为:" + new SimpleDateFormat("yyyy-MM-dd: HH:mm:ss").format(new Date(System.currentTimeMillis())));
        }
    }
   //jiraDataScheduler的线程
    private Runnable doTask() {
        return new Runnable() {
            @Override
            public void run() {
                // 业务逻辑
                log.info("jiraDataScheduler开始执行,时间为:" + new SimpleDateFormat("yyyy-MM-dd: HH:mm:ss").format(new Date(System.currentTimeMillis())));
                jiraDataScheduler.getJiraInfo();
                log.info("jiraDataScheduler执行完毕,时间为:" + new SimpleDateFormat("yyyy-MM-dd: HH:mm:ss").format(new Date(System.currentTimeMillis())));
            }
        };
    }

    private Trigger getTrigger() {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 触发器
                CronTrigger trigger = null;
                try {
                    trigger = new CronTrigger(getCron());
                    return trigger.nextExecutionTime(triggerContext);
                } catch (Exception e) {
                    log.error("cron表达式不合法,系统已默认每天18点执行一次");
                }
                trigger = new CronTrigger("0 0 18 * * *");
                return trigger.nextExecutionTime(triggerContext);
            }
        };
    }

    public String getCron() {
        Cron cron = cronMapper.getCron();
        //如果数据库没有cron规则,默认cron="0 0 1 * * *"
        Cron cron1 = new Cron();
        cron1.setCron_id(1);
        cron1.setSeconds("0");
        cron1.setMinutes("0");
        cron1.setHours("1");
        cron1.setDayofMonth("*");
        cron1.setDayofWeek("*");
        cron1.setMonth("*");
        if (Objects.isNull(cron)) {
            cronMapper.addCron(cron1);
            cron = cron1;
        }

        String seconds = cron.getSeconds();
        String minutes = cron.getMinutes();
        String hours = cron.getHours();
        String dayofMonth = cron.getDayofMonth();
        String month = cron.getMonth();
        String dayofWeek = cron.getDayofWeek();

        String s = cron.toString();
        s = seconds + " " + minutes + " " + hours + " " + dayofMonth + " "
                + month + " " + dayofWeek;

        if (!s.equals(Task.cron)) {
            log.info(new StringBuffer("cron将改变为: ").append(s).append("旧的cron为: ").append(Task.cron).append("'").toString());
            Task.cron = s;
        }
        return Task.cron;
    }
}

6.数据库
CREATE DATABASE /!32312 IF NOT EXISTS/task /*!40100 DEFAULT CHARACTER SET utf8 */;

USE task;
/*Table structure for table cron */

DROP TABLE IF EXISTS cron;
CREATE TABLE cron (
cron_id varchar(10) NOT NULL COMMENT ‘主键’,
seconds varchar(10) NOT NULL COMMENT ‘秒’,
minutes varchar(10) NOT NULL COMMENT ‘分’,
hours varchar(10) NOT NULL COMMENT ‘时’,
dayOfMonth varchar(10) NOT NULL COMMENT ‘天’,
dayOfWeek varchar(10) NOT NULL COMMENT ‘月’,
month varchar(10) NOT NULL COMMENT ‘周’,
PRIMARY KEY (cron_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值