java定时任务

方式一:基于注解@Scheduled实现简单定时器

image.png

DemoApplication文件

package com.example.schedule.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(value = "com.example.schedule.schedule")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

MySchedule文件

package com.example.schedule.schedule;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@EnableScheduling
@Configuration
public class MySchedule {

    @Scheduled(fixedRate = 3000)
    private void configureTasks1() {
        System.out.printf("xxxx");
    }

    @Scheduled(fixedRate = 6000)
    private void configureTasks2() {
        System.out.printf("xxxx");
    }
}

注解含义

 * @Scheduled(cron = "0/5 * * * * ?") //每隔5s执行一次
 * @Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
 * @Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次

方式二:基于接口SchedulingConfigurer的动态定时任务


image.png
package com.example.schedule.schedule;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

@Configuration
@EnableScheduling
public class DynamicSchedule implements SchedulingConfigurer {


    /**
     * 测试数据,实际可从数据库获取
     */
    private List tasks = Arrays.asList(
            new Task(1, "任务1", "*/3 * * * * *"),
//            new Task(2, "任务2", "*/3 * * * * *"),
//            new Task(3, "任务3", "*/3 * * * * *"),
//            new Task(4, "任务4", "*/3 * * * * *"),
//            new Task(5, "任务5", "*/3 * * * * *"),
//            new Task(6, "任务6", "*/3 * * * * *"),
//            new Task(7, "任务7", "*/3 * * * * *"),
//            new Task(8, "任务8", "*/3 * * * * *"),
//            new Task(9, "任务9", "*/3 * * * * *"),
            new Task(10, "任务10", "*/3 * * * * *")
    );

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(taskScheduler());

        tasks.forEach(task -> {
            //任务执行线程
            Runnable runnable = () -> {
                System.out.println("execute task :" + task.getId());
                System.out.println(Thread.currentThread());
            };

            //任务触发器
            Trigger trigger = triggerContext -> {
                //获取定时触发器,这里可以每次从数据库获取最新记录,更新触发器,实现定时间隔的动态调整
                CronTrigger cronTrigger = new CronTrigger(task.getCron());
                return cronTrigger.nextExecutionTime(triggerContext);
            };

            //注册任务
            scheduledTaskRegistrar.addTriggerTask(runnable, trigger);
        });

        //1
//        scheduledTaskRegistrar.addCronTask(new Runnable() {
//
//            @Override
//            public void run() {
//                log.warn(name+" --- > 开始");
//                //业务逻辑
//                log.warn(name+" --- > 结束");
//            }
//        }, cron);  //加入时间
    }

    /**
     * 设置TaskScheduler用于注册计划任务
     *
     * @return
     */
    @Bean
    public Executor taskScheduler() {
        ThreadPoolTaskScheduler t = new ThreadPoolTaskScheduler();
        t.setPoolSize(2);
        t.setThreadNamePrefix("taskScheduler - ");
        t.initialize();
        return t;
    }

    static class Task {
        /**
         * 主键ID
         */
        private int id;
        /**
         * 任务名称
         */
        private String name;
        /**
         * cron表达式
         */
        private String cron;

        public Task(int id, String name, String cron) {
            this.id = id;
            this.name = name;
            this.cron = cron;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        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;
        }
    }
}

你可能感兴趣的:(java定时任务)