Application of java scheduling task in project

Preface

Task scheduling refers to the automatic execution of tasks based on a given time point, a given time interval or a given number of executions. There are unique application scenarios in the project, such as synchronizing data every morning, operating business regularly and so on.

  • Timer
  • scheduler
  • quartz

1 Timer

java.util.Timer, can achieve some simple timing tasks. Timer and TimerTask are the core classes of task scheduling using Timer. Timer is responsible for setting the start and interval execution time of TimerTask. Users only need to create an inheritance class of TimerTask, implement their own run method, and then throw it to Timer to execute.
Timer drops the received tasks into his TaskList, which is sorted according to Task's initial execution time. TimerThread starts as a daemon thread when it creates Timer. This thread polls all tasks, finds a task to be executed recently, and then hibernates. When it reaches the starting point of the task to be executed recently, TimerThread is awakened and executed. TimerThread then updates the latest task to be performed and continues to sleep as follows.
Timer has the advantage of simplicity and ease of use, but because all tasks are scheduled by the same thread, all tasks are executed serially, and only one task can be executed at the same time. The delay or exception of the former task will affect the later task:

public class TimerTest extends TimerTask {
    private String jobName = "";

    public TimerTest(String jobName) {
        super();
        this.jobName = jobName;
    }

    @Override
    public void run() {
        System.out.println("execute " + jobName);
    }

    public static void main(String[] args) {
        Timer timer = new Timer();
        long delay1 = 1 * 1000;
        long period1 = 1000;
        // One second from now, job1 is executed every 1 second
        timer.schedule(new TimerTest("job1"), delay1, period1);
        long delay2 = 2 * 1000;
        long period2 = 2000;
        // Two seconds from now on, job2 is executed every two seconds
        timer.schedule(new TimerTest("job2"), delay2, period2);

    }
}

java

scheduler single-machine service scheduling strategy commonly used.

2.xml configuration

                <beans xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/task   http://www.springframework.org/schema/task/spring-task-3.1.xsd">

                <task:executor id="executor" pool-size="15" />  
                <task:scheduler id="scheduler" pool-size="30" />  
                <task:annotation-driven executor="executor" scheduler="scheduler" />

2. The time setting of cornexpression can be referred to. corn expression -- used to set timing tasks

                @Scheduled(cron = "*/5 * * * * *")
                public void test1() throws InterruptedException {
                log.info("test1, 5 Execute once a second, every time sleep 8s");
                }

3. Notes:

  • 3.1 For the same timed task, the second trigger time is up. Will it be executed before the first one is completed? No, it will wait until the last execution is completed before the next one is executed.
  • 3.2 Do different scheduled tasks affect each other? Depending on the number of available timed task threads, if the number of available timed task threads is sufficient, it will not affect; if the number of available timed task threads is less than the number of timed tasks to be executed, the failure to obtain the thread will naturally wait until there are idle threads to execute.

quartz cluster Publishing web server task strategy

It can be solved that if a cluster publishes a web server, it will cause each server to run the timer once, and the timer will be executed many times. Quartz can solve this problem. quartz is implemented by a timer selection server execution mechanism, which is completed with Java Web server and database, so that only one suitable web server is selected to perform the timing task each time.

1. Configuring maven dependencies

                <!-- Timing task -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
        </dependency>

2.Scheduler Scheduler Scheduler Configuration

<description>Quartz Timing Cluster Task Configuration</description>
    <bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!--Must, QuartzScheduler Delayed startup, after application startup QuartzScheduler Restart -->
        <property name="startupDelay" value="60"/>
        <!-- Common flip-flops: list of flip-flops -->
        <property name="triggers">
            <list>                
                <ref local="syncFacTimerTrigger"/>
            </list>
        </property>
        <property name="quartzProperties">
            <props>
                <!-- It's mainly this parameter. -->
                <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
                <prop key="org.terracotta.quartz.skipUpdateCheck">true</prop>
            </props>
        </property>
    </bean>

3. Configuration of Trigger Flip-flops

<!--Cron Expression trigger-->
    <bean id="syncFacTimerTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="QuartzSyncFacJob"/> <!-- Executing a timed task triggered by a trigger bean -->
        </property>
        <property name="cronExpression">
             <value>0 0/30 * * * ?</value>  <!--30 Once a minute-->
            <!--  <value>0 0/1 * * * ?</value> --> <!-- 1 Once a minute -->
            <!--<value>0 0 2 * * ?</value> <!–2 o'clock everyday –>-->
            <!--<value>0 0/1 * * * ?</value> 1 Once a minute -->
        </property>
    </bean>

4.Job Scheduling Task Configuration

<bean id="QuartzSyncFacJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <!-- durability Indicates whether the task remains in the database after completion, by default false -->
        <property name="durability" value="true"/>
        <!-- Target class /wmuitp/src/test/SpringQuartz.java -->
        <property name="jobClass" value="com.hec.dup.web.schedule.QuartzSyncFacJob"/><!--Task class-->
        <property name="applicationContextJobDataKey" value="applicationContext"/>
        <property name="jobDataAsMap"><!-- It's very important for us to use it for the purpose of __________ JobDetail Biography -->
            <map>
                <entry key="dupMgrOrgReviseDoService" value-ref="dupMgrOrgReviseDoService"/><!--Injected servise Name-->
            </map>
        </property>
    </bean>

5 Job class for processing related business logic

public class QuartzSyncFacJob extends QuartzJobBean {
    private static Logger logger = LoggerFactory.getLogger(QuartzJobBean.class);

    @Override
    public void executeInternal(JobExecutionContext context) throws JobExecutionException {
        syncData(context);
    }

    public void syncData(JobExecutionContext context) {
        //Beans are injected into jobDataAsMap and retrieved
        IDupMgrOrgReviseDoService dupMgrOrgReviseDoService = (IDupMgrOrgReviseDoService) context.getJobDetail().getJobDataMap().get("dupMgrOrgReviseDoService");
                //Processing related logic
        dupMgrOrgReviseDoService.syncSaveOrUpMdcFactory(); 
    }

}

These are routine tasks scheduling, of course spring provides a variety of scheduling injection methods, in addition to bean s, there are also a variety of @ injection methods, interested in their own research.

Tags: Java Web Server Spring Database

Posted on Mon, 22 Apr 2019 12:30:34 -0700 by PhdJB