1. 程式人生 > >springBoot+scheduling實現多工動態定時任務

springBoot+scheduling實現多工動態定時任務

 使用spring自帶的scheduling定時排程任務相當於輕量級的Quartz,但是不支援分散式,若要實現分散式定時任務就得使用Quartz了.

第一步,在入口類中宣告定時任務

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling //宣告定時任務
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}

第二步,建立定時任務物件,需要實現SchedulingConfigurer介面,其中有兩個入參doTask業務邏輯,getTrigger觸發器

import com.zenithink.demo.controller.MyDynamicTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
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;

//@Component
public class ScheduledUtil implements SchedulingConfigurer {

    private static Logger log = LoggerFactory.getLogger(MyDynamicTask.class);

    private  String cron="0/10 * * * * ?";

    private String name="測試";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(doTask(), getTrigger());
    }

    /**
     * 業務執行方法
     * @return
     */
    private Runnable doTask() {
        return new Runnable() {
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                // 業務邏輯
                log.info(name+",時間為:" + simpleDateFormat.format(new Date()));
            }
        };
    }

    /**
     * 業務觸發器
     * @return
     */
    private Trigger getTrigger() {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 觸發器
                CronTrigger trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            }
        };
    }
}

第三步,建立多個定時任務物件,並注入spring容器

import com.zenithink.demo.utils.ScheduledUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.Name;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class MyDynamicTask  {

    private static Logger log = LoggerFactory.getLogger(MyDynamicTask.class);

    @Autowired
    @Qualifier("test1")
    private ScheduledUtil scheduledUtil1;

    @Autowired
    @Qualifier("test2")
    private ScheduledUtil scheduledUtil2;

    @Autowired
    @Qualifier("test3")
    private ScheduledUtil scheduledUtil3;


    @GetMapping
    public void getCron(String time,String name,Integer task) {
        if(task==1){
            scheduledUtil1.setCron(time);
            scheduledUtil1.setName(name);
        }else if(task==2){
            scheduledUtil2.setCron(time);
            scheduledUtil2.setName(name);
        }else if (task==3){
            scheduledUtil3.setCron(time);
            scheduledUtil3.setName(name);
        }
    }
}

執行日誌示例: