Springboot添加定时器任务

本文介绍如何在Spring框架中使用定时任务,并通过实例演示如何动态修改定时任务的执行周期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  当在固定时间,比如月末生成一些报表或者一些固定任务时,我们使用定时器。

1.定时器需要在  ①启动类增加@EnableScheduling注解,使项目能够识别定时器类   ②使定时器类能够被扫描到 一般加@Compoment   @Configuration

下面为定时器方法
    @Scheduled(cron = "0 0/2 * * * *")
    public LFResultBean timer(){
        //获取当前时间
        if (timerMap.get("cmStandardCityConfigFindDto")!=null){
            LocalDateTime localDateTime =LocalDateTime.now();
            new LFResultBean(iCmStandardCityConfigService.cmStandardCityConfigFind(timerMap.get("cmStandardCityConfigFindDto")));
            System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        return new LFResultBean();
    }

 定时器为没有参数的 如果想传入参数 那么就应该设置全局变量 然后程序赋值 然后定时器中使用
 

private static Map<String,Object> timerMap = new HashMap();

timeMap.put("name","liyu");

定时器得到
timeMap.get("name");
@Scheduled(cron = "0 0/2 * * * *") 注解类似Liunx的定时任务
包含6~7个参数
秒 分 小时  每月的第几天  月份  星期几   年(固定为1970~2099)

0/2 * * * * * 每隔2s执行 /n 意为每隔几秒执行

 

 

Liunx的定时任务

vim  /etc/crontab
minute hour day month dayofweek command

 

继承并可以添加参数

package com.qwrt.fire.sensor.task;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * Created by jack on 2018/3/22.
 */
@Component
public class MyScheduledTaskTest implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(MyScheduledTaskTest.class);
    private static int fixedDelayCount = 0;
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
    private static final String DEFAULT_CRON = "0/5 * * * * ?";
    private String cron = DEFAULT_CRON;
 
 
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            //定时业务处理
            if (!cron.equals(DEFAULT_CRON)) {
                System.out.println("定时参数修改了: "+fixedDelayCount++);
            }
            // 定时任务的业务逻辑
            logger.info("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
        }, triggerContext -> {
            // 定时任务触发,可修改定时任务的执行周期
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecDate = trigger.nextExecutionTime(triggerContext);
            return nextExecDate;
        });
    }
 
    public String getCron() {
        return cron;
    }
 
    public void setCron(String cron) {
        this.cron = cron;
    }
}

Controller

package com.qwrt.fire.sensor.task;
 
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * Created by jack on 2018/3/22.
 */
@RestController
@RequestMapping("test/modifyScheduledParamTest")
public class ModifyScheduledParamTest {
    @Autowired
    private MyScheduledTaskTest myScheduledTaskTest;
    @RequestMapping(value = "/updateCron")
    public JSONObject updateCron(){
 
        System.out.println("进行定时参数修改......");
        String cron = "0/10 * * * * ?";
        myScheduledTaskTest.setCron(cron);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", "修改定时参数成功");
        return jsonObject;
    }
}

 

转载于:https://www.cnblogs.com/bockpecehhe/p/9254493.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值