Follow the example to learn java multi-thread 10-scheduled task instance

Source: Internet
Author: User

Follow the example to learn java multi-thread 10-scheduled task instance

Scheduled tasks are often used in business scenarios. Many of our features require such technologies to implement them. For example, you can obtain some data in a scheduled manner and push it out to regularly process cleanup tasks, regularly checks a value. So how can we implement it? What should we pay attention to during implementation?

Scheduled tasks are executed by another thread, which is also a type of concurrency. It may be hard for everyone to understand. It is said that timing is not executed at the time. How can we still generate concurrency, here we mainly look at two indicators: one is the execution frequency, and the other is the time of each execution. If the execution frequency is high and the execution time is very time-consuming, then concurrency is formed, of course, there is also a situation where the scheduled job calls methods of other classes, while the normal business logic also calls methods of that class, at this time, it is also possible that a concurrent call to that class may occur at a certain coincidence time.

Therefore, we should pay attention to the following two points when writing scheduled tasks:

1: If the execution frequency is high and the task execution time is too long, add synchronization processing to the job execution method.

2: If the job calls other class methods, the methods provided by other classes should also be released to thread security.

The following example shows how to implement a scheduled task:

1: timer provided by java

Package com. home. thread. thread10; import java. util. Date; import java. util. Timer;/*** @ author gaoxu * to learn it! */Public class TimerMain {/*** @ param args */public static void main (String [] args) {Timer timer = new Timer (); timer. schedule (new TimerTaskThread (), new Date (), 2000 );}}


Package com. home. thread. thread10; import java. util. Date; import java. util. TimerTask;/*** @ author gaoxu * to learn it! */Public class TimerTaskThread extends TimerTask {// The constructor without parameters public TimerTaskThread () {}// you can also write the constructor with parameters @ Overridepublic synchronized void run () {System. out. println (new Date (). toString () + "Timer method, I will execute it once every two seconds"); // you can write your own scheduled business here }}

This is a scheduled task implemented by timer. The running result is as follows:

Sat Feb 07 01:25:31 CST 2015, Timer mode, I run the Sat Feb 07 01:25:33 CST 2015 in two seconds, Timer mode, I run the Sat Feb 07 01:25:35 CST 2015 in two seconds, timer mode. It takes two seconds to execute the Sat Feb 07 01:25:37 CST 2015. Timer mode.

2: scheduled tasks implemented by the open-source Quartz framework

Package com. home. thread. thread10; import org. quartz. scheduler; import org. quartz. schedulerException; import org. quartz. schedulerFactory; import org. quartz. impl. stdSchedulerFactory; import com. home. jobServiceImpl;/***** @ author gaoxu! */Public class SchedulerMain {public static void main (String [] para) {try {SchedulerFactory sf = new StdSchedulerFactory (); Scheduler schedfactory = sf. getScheduler (); JobServiceImpl jobService = new JobServiceImpl (); jobService. setScheduler (schedservice); jobService. platDataCollectInterval (2);} catch (SchedulerException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}


Package com. home; import org. quartz. jobBuilder; import org. quartz. jobDetail; import org. quartz. scheduler; import org. quartz. schedulerException; import org. quartz. simpleScheduleBuilder; import org. quartz. trigger; import org. quartz. triggerBuilder; import com. home. job. testJob;/*** @ author gaoxu! */Public class JobServiceImpl {private Scheduler scheduler; public void setScheduler (Scheduler scheduler) {this. scheduler = schedval;} public scheduler getScheduler () {return Scheduler;} public void platDataCollectInterval (int interval) throws SchedulerException, Exception {System. out. println ("update PlatDataCollect cycle start"); JobDetail jobDetail = JobBuilder. newJob (TestJob. class ). withIdentity ("testJob_1", "group_1 "). build (); Trigger trigger = TriggerBuilder. newTrigger (). withIdentity ("trigger_1", "group_1 "). withSchedule (SimpleScheduleBuilder. repeatSecondlyForever (interval )). build (); scheduler. scheduleJob (jobDetail, trigger); scheduler. start ();}}

package com.home.job;import java.util.Date;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;public class TestJob implements Job{@Overridepublic synchronized void execute(JobExecutionContext arg0) throws JobExecutionException { System.out.println("test job date:" + new Date().toString());  }}


There are three types, where the job class is the executor of the task, Scheduler is a Scheduler, the Scheduler can create multiple triggers, each Trigger can execute a job.

log4j:WARN No appenders could be found for logger (org.quartz.impl.StdSchedulerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.update  PlatDataCollect cycle starttest job date:Sat Feb 07 01:30:31 CST 2015test job date:Sat Feb 07 01:30:33 CST 2015test job date:Sat Feb 07 01:30:35 CST 2015test job date:Sat Feb 07 01:30:37 CST 2015


3: Implemented by threads

Package com. home. thread. thread10;/*** @ author gaoxu! */Public class ThreadMain {public static void main (String [] para) {ThreadTask threadTask = new ThreadTask (); threadTask. start ();}}



Package com. home. thread. thread10; import java. util. date; public class ThreadTask extends Thread {public void run () {while (true) {try {Thread. sleep (1, 2000); System. out. println (new Date (). toString () + "thread mode, I run it once every two seconds"); // you can write the scheduled service you want to implement here} catch (InterruptedException e) {e. printStackTrace ();}}}}


Running result:

Sat Feb 07 01:33:34 CST 2015 thread mode. I run the Sat Feb 07 01:33:36 CST 2015 thread mode every two seconds. I run the Sat Feb 07 01:33:38 CST 2015 thread mode every two seconds, I run the Sat Feb 07 01:33:40 CST 2015 thread every two seconds. I run the Sat Feb 07 01:33:42 CST 2015 thread every two seconds. I run the Sat Feb once every two seconds.


There are also many ways to implement work tasks, such as java. util. concurrent. ScheduledThreadPoolExecutor. Here is not an example.

Pay attention to the concurrency of scheduled tasks to avoid concurrent errors.



Zookeeper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.