springboot perform regular tasks in several ways

springboot create a scheduled task in three ways:
1. annotation-based (@Scheduled)
2. Based Interface (SchedulingConfigurer)
3. Timing annotation-based multi-threaded task

1. annotation-based way to use

package com.club.business.scheduletask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalDateTime;

/**
 * 定时任务配置类
 *
 * @Configuration 主要用于标记配置类,兼备Component的效果
 * @EnableScheduling 开启定时任务
 * @author Tom
 * @date 2019-12-18
 */
@Configuration
@EnableScheduling
public class MyScheduleTask {

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

    /**
     * 添加定时任务(指定定时任务执行时间间隔,例如:5秒)
     * 或使用fixedRate @Scheduled(fixedRate=5000)也表示每5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() {
        /**
         * 此处可添加执行任务中的业务逻辑
         */
        log.info("执行静态定时任务时间: " + LocalDateTime.now());
    }
}

2. Based on the interface work

/**
* 基于接口方式的定时任务
* @Configuration 主要用于标记配置类,兼备Component的效果
* @EnableScheduling 开启定时任务
* 注意:需要实现接口 SchedulingConfigurer
* @author Tom
* @date 2019-12-18
*/
@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Autowired
    CronMapper cronMapper;

    /**
     * 重写定时任务方法
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		/**添加任务*/
        taskRegistrar.addTriggerTask(
        		/**
        		* 添加需要执行的业务逻辑
        		*/
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                /**设置执行任务的周期*/
                triggerContext -> {
                    /**从数据库获取配置的执行周期(此处采用)
                    * 可以将执行周期配置在配置文件中获取
                    */
                    String cron = cronMapper.getCron();
                    /**判断取出的周期配置是否为空*/
                    if (StringUtils.isBlank(cron)) {
                        /**数据为空则执行重新获取逻辑*/
                    }
                    /**最后返回执行周期*/
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}

3. The multi-threaded tasks based on the timing annotation style

/**
* 基于注解的方式实现多线程定时任务
* @Configuration 主要用于标记配置类,兼备Component的效果
* @EnableScheduling 开启定时任务
* @EnableAsync 开启多线程
* 注意:需要实现接口 SchedulingConfigurer
* @author Tom
* @date 2019-12-18
*/
@Configuration
@EnableScheduling
@EnableAsync
public class MultithreadScheduleTask {
		
		/**
		* 使用 fixedDelay 的方式设置时间间隔为1秒
		* @Async注解开启一个线程,重要
		*/
        @Async
        @Scheduled(fixedDelay = 1000)
        public void first() throws InterruptedException {
            System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
            System.out.println();
            Thread.sleep(1000 * 10);
        }

        @Async
        @Scheduled(fixedDelay = 2000)
        public void second() {
            System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
            System.out.println();
        }
    }

appendix:

On timer time setting mode as follows:
a CronTrigger configured to the full format: [sec] [min] [h] [day] [month] [weeks] [in]
Example:

0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
0 0 12 ? * WED 表示每个星期三中午12点
"0 0 12 * * ?" 每天中午12点触发
"0 15 10 ? * *" 每天上午10:15触发
"0 15 10 * * ?" 每天上午10:15触发
"0 15 10 * * ? *" 每天上午10:15触发
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发
"0 15 10 15 * ?" 每月15日上午10:15触发
"0 15 10 L * ?" 每月最后一日的上午10:15触发
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发
No. Explanation Required Which allowed the value of Allow wildcard
1 second Yes 0-59 , - * /
2 Minute Yes 0-59 , - * /
3 Time Yes 0-23 , - * /
4 day Yes 1-31 , - * ? / L W
5 month Yes 1-12 or JAN-DEC , - * /
6 week Yes 1-7 or SUN-SAT , - * ? / L W
7 year no empty or 1970-2099 , - * /

Wildcard Description:

  • Represent all the values ​​such as: is provided on the sub-fields "*" indicates trigger every minute

? Said they did not specify the value. Scene used to not care about the value of the current setting of this field.

For example: To trigger on the 10th of each month of operation, but is not concerned about a few weeks, so it is necessary that the field is set for the specific peripheral position is set to 00010 * "?"?

  • Representing the interval. For example, set up "10-12" on the hour, 10, 11, represents the point will be triggered.

Indicating specify multiple values, such as setting "MON, WED, FRI" in the week field said on Monday, Wednesday and Friday trigger

/ For incrementing trigger. As set "5/15" above represents the second for 5 seconds, every 15 seconds by a trigger (5,20,35,50). Set in the month field '1/3' Start No. 1 a month, once every three days triggered shown.

L represents the final meaning. On the field, set the day, represents the last day (based on the current month, if February is also based on whether it is a leap year [leap]) the month, expressed Saturday, the equivalent of "7" or "SAT" in the week field. If the "L" digitally before, indicates the last of the data. For example, setting this format "6L" in the week field, it means "the last Friday of the month."

W represents the example set "15W" on the daily field closest to the date specified weekday (Monday to Friday), represents the 15th of each month from recent days that trigger. If the 15th happens to be Saturday, you find the nearest Friday (14) is triggered, if the number 15 is the weekend, then look for the nearest next Monday (16) is triggered. If the number in just 15 working days (Monday to Sunday e), then triggered in the day. If you specify the format of "1W", it said 1 month later recent days triggered. If Saturday is the No. 1, No. 3 will be triggered Monday. (Note, "W" can only be set before the specific numbers are not allowed interval "-").

# Serial number (the first few weeks of every month a few), for example on the field Week "6 # 3". Note that if you specify "# 5", not just the fifth week of the third week of the month Saturday Sixth, the configuration is not triggered (with mother's Day and father's Day a perfect fit);

Tip:
'L' and 'W' may be used in combination. If set to "LW" in the Japanese field, then in the last business day of the month trigger;
set the week field, the use of English letters are not case sensitive, and that is the same as MON mon;

Published 14 original articles · won praise 2 · Views 796

Guess you like

Origin blog.csdn.net/breakaway_01/article/details/103597351
Recommended