美文网首页
java定时任务

java定时任务

作者: xiari1991 | 来源:发表于2020-12-21 15:29 被阅读0次

方式一:基于注解@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<Task> 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定时任务调度工具详解

    本篇内容:什么是定时任务调度?Java定时任务调度工具详解之 Timer篇Java定时任务调度工具详解之 Quar...

  • Spring Boot 定时任务

    为什么需要定时任务 生活中定时任务的需求越来越多,场景也越来越多 如何实现定时任务 Java自带的java.uti...

  • java定时器

    java定时器 什么是Java定时器?Java 定时器就是在给定的间隔时间执行自己的任务; Java实现定时器有以...

  • Dubbo——时间轮(Time Wheel)算法应用

    定时任务 Netty、Quartz、Kafka 以及 Linux 都有定时任务功能。 JDK 自带的 java.u...

  • java中的定时器

    1、java中普通定时任务 Timer定时器 ScheduledThreadPoolExecutor 定时器 Ti...

  • 一文教你实现Java、Spring动态启停定时任务

    为什么需要定时任务 定时任务的应用场景十分广泛,如定时清理文件、定时生成报表、定时数据同步备份等。 Java定时任...

  • 拥抱Kubernetes,再见了,SpringBoot cron

    项目开发中总是需要执行一些定时任务,比如定时处理数据之后发送邮件,定时更新缓存等等。 Java定时任务 基于 ja...

  • java定时任务

    1.监听类继承ServletContextListener public class MyListen imple...

  • java定时任务

    Java开发过程中经常会遇到使用定时任务的情况,我总结了一下有如下四种方式:Timer、ScheduledExec...

  • Java 定时任务

    在java中一个完整定时任务需要由Timer、TimerTask两个类来配合完成。 Timer类 Timer是一种...

网友评论

      本文标题:java定时任务

      本文链接:https://www.haomeiwen.com/subject/llrrnktx.html