The most complete and detailed explanation and examples of Spring timed tasks in history

1. The most primitive timed task

1. Adopt thread method

public static void runTask(){
        final long timeInterval = 1000;
        Runnable runnable = new Runnable() {
            public void run() {
                while (true){
                    System.out.println("hello");
                    try {
                        Thread.sleep(timeInterval);
                    }catch (InterruptedException e){
                        e.printStackTrace ();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

Second, use the Timer class in jdk

package com.flx.timer;

import com.flx.timer.task.SimpleTask;
import com.flx.timer.task.SimpleTaskLiving;
import com.flx.util.BaseFunction;
import com.flx.util.date.CalendarUtils;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Fenglixiong on 2017/9/25.
 */
public class TimerHome {

    private static Timer timer = new Timer();

    public static void main(String[] args) {

        TaskOne(10);
        TaskTwo(CalendarUtils.addSeconds(new Date(),10));
        TaskThree(CalendarUtils.addSeconds(new Date(),10));
        TaskFour();
        TaskFive(CalendarUtils.addSeconds(new Date(),10));
        TaskSix ();
        TimerTaskPool ();
        TimerTask01();
        TimerTask02();
    }

    /**
     * Specify the delay time to execute the scheduled task
     * @param time
     */
    public static void TaskOne(int time){
        BaseFunction.console("Prepare to execute task TaskOne...");
        Timer timer = new Timer ();
        timer.schedule(new SimpleTask(),time*1000);
    }

    /**
     * Execute the task at the specified time
     * @param date
     */
    public static void TaskTwo(Date date){
        BaseFunction.console("Prepare to execute the task TaskTwo...");
        CalendarUtils.sayTime(new Date());
        Timer timer = new Timer ();
        timer.schedule(new SimpleTask(),date);
    }

    /**
     * Execute at the specified time and then execute the task at the specified time interval
     * @param date
     */
    public static void TaskThree(Date date){
        BaseFunction.console("Prepare to execute the task TaskThree...");
        CalendarUtils.sayTime(new Date());
        Timer timer = new Timer ();
        timer.schedule(new SimpleTaskLiving("TaskThree"),date,3000);
    }

    /**
     * Execute after the specified time delay and then execute the task at the specified time interval
     *
     */
    public static void TaskFour(){
        BaseFunction.console("Prepare to execute the task TaskFour...");
        CalendarUtils.sayTime(new Date());
        Timer timer = new Timer ();
        timer.schedule(new SimpleTaskLiving("TaskFour"),5000,3000);
    }

    /**
     * Execute after the specified time delay and then execute the task at the specified time interval
     *
     */
    public static void TaskFive(Date firstTime){
        BaseFunction.console("Prepare to execute the task TaskFive...");
        CalendarUtils.sayTime(new Date());
        Timer timer = new Timer("TaskFive");
        timer.scheduleAtFixedRate(new SimpleTaskLiving(),firstTime,3000);
    }

    /**
     * Execute after the specified time delay and then execute the task at the specified time interval
     *
     */
    public static void TaskSix(){
        BaseFunction.console("Prepare to execute task TaskSix...");
        CalendarUtils.sayTime(new Date());
        Timer timer = new Timer ();
        timer.scheduleAtFixedRate(new SimpleTaskLiving("TaskSix"),20000,3000);
    }

    /**
     * TimerTask01();
     * TimerTask02();
     * Execute both tasks at the same time
     * 1. If it is two Timers, it is equivalent to two threads that will not affect each other
     * 2. If it is a Timer, plan to execute two timed tasks
     * One of the delays or blocking will affect the execution of the other task
     */
    public static void TimerTask01(){
        CalendarUtils.sayTime(new Date());
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("start:TimerTask01");
                try {
                    BaseFunction.console("Run:--->TimerTask01");
                    Thread.sleep(15000); //Thread sleeps for 3000
                    BaseFunction.console("After sleep--->TimerTask01");
                    CalendarUtils.sayTime(new Date());
//                    throw new RuntimeException();
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }
        }, 1000);
    }

    public static void TimerTask02(){
        CalendarUtils.sayTime(new Date());
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("运行:TimerTask02");
                CalendarUtils.sayTime(new Date());
//                throw new RuntimeException("...");
            }
        }, 5000);
    }

    /**
     * ScheduledExecutorService is from java.util.concurrent of Java SE5,
     * Introduced as a concurrent tool class, this is the ideal way to implement timed tasks.
     */
    public static void TimerTaskPool(){

        Runnable runnable = new Runnable() {
            public void run() {
                // task to run goes here
                System.out.println("Hello !!");
            }
        };

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.scheduleAtFixedRate(runnable,10,1, TimeUnit.SECONDS);

    }

}

/**
 schedule(TimerTask task, Date time): Schedule the execution of the specified task at the specified time.
 schedule(TimerTask task, Date firstTime, long period) : Schedule the specified task to start at the specified time for repeated fixed-delay execution.
 schedule(TimerTask task, long delay) : Schedule the specified task to be executed after the specified delay.
 schedule(TimerTask task, long delay, long period) : Schedules the specified task for repeated fixed-delay execution starting after the specified delay.
 At the same time, the scheduleAtFixedRate method is also overloaded. The scheduleAtFixedRate method is the same as the schedule, but their focus is different, which will be analyzed later.
 scheduleAtFixedRate(TimerTask task, Date firstTime, long period): Schedules the specified task to start at the specified time for repeated fixed-rate execution.
 scheduleAtFixedRate(TimerTask task, long delay, long period): Schedules the specified task to begin repeated fixed-rate execution after the specified delay.
 */

/**
 * TimerTask

 The TimerTask class is an abstract class that is scheduled by a Timer as a one-time or recurring task. It has an abstract method run() method,
 This method is used to perform the action to be performed by the corresponding timer task. Therefore, each specific task class must inherit TimerTask and then override the run() method.
 In addition it has two non-abstract methods:
 boolean cancel(): Cancels this timer task.
 long scheduledExecutionTime(): Returns the scheduled execution time of the most recent actual execution of this task.
 */

Three, Spring's own integrated Task task

(1) Configuration file method

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <!--This task is written to the annotation and executed-->
    <!--<task:scheduled-tasks>-->
        <!--<task:scheduled ref="simpleTaskJob" method="jobOne" cron="0/2 * * * * ?"/>-->
    <!--</task:scheduled-tasks>-->
    
    <!--News grab-->
    <task:scheduled-tasks>
        <task:scheduled ref="simpleTaskService" method="sayHello" cron="0/2 * * * * ?" fixed-delay="1000"/>
    </task:scheduled-tasks>

    <!--Bond Grab-->
    <task:scheduled-tasks>
        <task:scheduled ref="simpleTaskService" method="sayGood" cron="0/5 * * * * ?" />
    </task:scheduled-tasks>

    <!--SSE E Interactive-->
    <task:scheduled-tasks>
        <task:scheduled ref="simpleTaskService" method="sayLove" cron="0/10 * * * * ?" />
    </task:scheduled-tasks>

    <!--Announcement-->
    <task:scheduled-tasks>
        <task:scheduled ref="simpleTaskService" method="sayNo" cron="0/15 * * * * ?" />
    </task:scheduled-tasks>

    <!--The number of stocks held by the Hong Kong Stock Exchange-->
    <task:scheduled-tasks>
        <task:scheduled ref="simpleTaskService" method="sayYes" cron="0/20 * * * * ?" />
    </task:scheduled-tasks>

</beans>

<!--

Field Allowed Values ​​Allowed Special Characters
seconds 0-59 , -*/
points 0-59 , -*/
hours 0-23 , -*/
Dates 1-31, -*?/LWC
Month 1-12 or JAN-DEC , - * /
Week 1-7 or SUN-SAT , -* ? / LC #
year (optional) leave blank, 1970-2099 , - * /
- Interval
* wildcard
? you don't want to set that field
Below are just a few examples

CRON expression meaning
"0 0 12 * * ?" triggers every day at 12:00 noon
"0 15 10 ? * *" fires every morning at 10:15
"0 15 10 * * ?" fires every morning at 10:15
"0 15 10 * * ? *" fires every morning at 10:15
"0 15 10 * * ? 2005" triggers every morning at 10:15 in 2005
"0 * 14 * * ?" fires every minute from 2pm to 2:59pm every day
"0 0/5 14 * * ?" fires every 5 minutes every day from 2pm to 2:55pm
"0 0/5 14,18 * * ?" Triggers every 5 minutes during the two time periods from 2pm to 2:55pm and from 6pm to 6:55pm every day
"0 0-5 14 * * ?" Triggers every minute from 14:00 to 14:05 every day
"0 10,44 14 ? 3 WED" Triggers every Wednesday at 14:10 and 14:44 in March
"0 15 10 ? * MON-FRI" Triggered at 10:15 every Monday, Tuesday, Wednesday, Thursday, Friday

-->


(2) Annotation method

First enable the annotation driver

<task:annotation-driven scheduler="poolScheduler" mode="proxy"/>
<task:scheduler id="poolScheduler" pool-size="10"/>

task class

@Service
public class SimpleTaskJob {

    private int count = 0;

    /**
     * After the annotation driver is configured in ApplicationContext.xml, the task is executed perfectly
     * Uncomment below can be executed
     */
    @Scheduled(cron = "0/2 * * * * ?")
    public void jobOne() {
        System.out.println("jobOne task..."+(++count));
    }

}


Fourth, Spring combined with Quartz to achieve precise timing tasks

(1) The most standard way of writing

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <!--1. Increase the thread pool for task registration-->
    <bean id="poolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <property name="corePoolSize" value="10"/>
        <property name="maxPoolSize" value="20"/>
        <property name="queueCapacity" value="500"/>
    </bean>

    <!--2. Define business logic processing class-->
    <bean id="simpleTask" class="com.flx.quartz.schedule.SimpleTask"/>

    <!--3. Add scheduling business logic-->
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="simpleTask"/>
        <property name="targetMethod" value="doTask"/>
    </bean>

    <!--4. Add scheduling trigger-->
    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"/>
        <property name="startDelay" value="3000"/>
        <property name="repeatInterval" value="2000"/>
    </bean>
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="jobDetail"/>
        <property name="cronExpression" value="0/3 * * * * ?"/>
    </bean>

    <!--5. Add scheduling-->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger"/>
                <ref bean="cronTrigger"/>
            </list>
        </property>
        <property name="taskExecutor" ref="poolTaskExecutor"/>
    </bean>
</beans>

(2) Complex Quartz calls

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

    <!--Timer data, optional -->
    <bean id="message" class="com.flx.app.entity.Message">
        <property name="status" value="100"/>
        <property name="message" value="very good"/>
    </bean>

    <bean id="methodTask" class="com.flx.quartz.schedule.MethodTask"/>

<!--Job task class start-->
    <!-- For times when you just need to invoke a method on a specific object -->
    <bean id="simpleTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="methodTask"/>
        <property name="targetMethod" value="sayHello"/>
    </bean>

    <bean id="firstComplexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.flx.quartz.schedule.FirstComplexJobDetail"/>
        <property name="jobDataMap">
            <map>
                <entry key="message" value-ref="message"/>
            </map>
        </property>
        <!--The trigger will not be deleted even if it is not associated-->
        <property name="durability" value="true"/>
    </bean>

    <bean id="secondComplexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.flx.quartz.schedule.SecondComplexJobDetail"/>
        <property name="durability" value="true"/>
    </bean>


    <!--If you need more advanced settings and need to pass data to the job, use this method if you want to be more flexible. -->
    <bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.flx.quartz.schedule.SimpleQuartzJob"/>
        <property name="jobDataMap">
            <map>
                <entry key="message" value-ref="message"/>
            </map>
        </property>
        <!--If a task is not durable, it will be automatically deleted when no trigger is associated with it. -->
        <property name="durability" value="true"/>
        <property name="description" value="Simple job implementation"/>
    </bean>
<!--Job task class end-->

<!--A Simple Trigger-->
    <!--The trigger to be used when configuring Quartz scheduling-->
    <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail" ref="simpleTask"/>
        <property name="startDelay" value="3000"/>
        <property name="repeatInterval" value="2000"/>
        <property name="repeatCount" value="4"/>
        <!--<property name="startTime" value=""/>-->
    </bean>
<!--B plan trigger-->
    <!-- This type is more flexible, allowing you to choose a schedule for a specific instance and how often to execute in the future. -->
    <bean id="firstCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="firstComplexJobDetail"/>
        <property name="cronExpression" value="0/5 * * ? * *"/>
    </bean>
    <bean id="secondCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="secondComplexJobDetail"/>
        <property name="cronExpression" value="0/10 * * ? * *"/>
    </bean>


<!--Integrate tasks and plans all before -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="simpleTrigger"/>
                <ref bean="firstCronTrigger"/>
                <ref bean="secondCronTrigger"/>
            </list>
        </property>
    </bean>

</beans>

Finally open the test class

public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("timer/spring-quartz-task.xml");
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("timer/simple-quartz-task.xml");
    }





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325811290&siteId=291194637