Java Implementation Timer Scheduledthreadpoolexecutor

Source: Internet
Author: User

Java Implementation Timer Scheduledthreadpoolexecutor

Deferred task: Perform the task after 100 seconds

Cycle tasks: Perform tasks every 10 seconds

There are some flaws in the timer and you should consider using schedulethreadpoolexecutor instead of him.

You can create objects of this class through the Schedulethreadpoolexecutor constructor or executors's Newschedulethreadpool factory method.

The timer creates only one thread when performing all scheduled tasks. If a task takes too long to execute, the timing accuracy of the other timertask is broken.

Another problem with the timer is that if Timetask throws an unchecked exception, the timer will show the behavior of the slot. The timer thread does not catch exceptions, so

The timed thread is terminated when TimerTask throws an unchecked exception. In this case, the timer will not resume the execution of the thread, but will mistakenly assume that the entire timer has disappeared.

As a result, timertask that have been dispatched but not yet executed will no longer be executed and the new task will not be dispatched. This is a thread leak.


Scheduledthreadpoolexecutor Inheritance Structure


execution of deferred and periodic tasks

The following code fragment

package com.usoft.schedule;import java.util.concurrent.callable;import  java.util.concurrent.executionexception;import java.util.concurrent.executors;import  java.util.concurrent.future;import java.util.concurrent.scheduledexecutorservice;import  java.util.concurrent.timeunit;/** *  @author:  lenovo (2015-08-13 23:54)  */public  Class scheduledtest {    public static void main (String args [])  throws ExecutionException, InterruptedException {         ScheduledExecutorService schedule = Executors                 .newscheduledthreadpool (2);         /**         *  delay 1 seconds to perform a task once           */   &nBsp;    schedule.schedule (new runnable ()  {              @Override              public void run ()  {                 system.out.println ("hello world runnable");             }        },  1000, timeunit.milliseconds);        /**          *  delay 2 seconds to perform a task once          */         future result = schedule.schedule (new  Callable<string> ()  {            @ Override     &nbSp;      public string call ()  throws Exception {                 return  "Hello  world callable ";            }         }, 2000, timeunit.milliseconds);         system.out.println (Result.get ());         //   Perform task         schedule.scheduleatfixedrate with fixed frequency (new  Runnable ()  {             @Override              public void run ()  {                 system.out.println (" Timed cycle task Execution ");             }        }, 1000,  2000, timeunit.milliseconds);        //  perform tasks in a periodic cycle with a fixed delay         schedule.schedulewithfixeddelay (new Runnable ()  {              @Override              public void run ()  {                 system.out.println ("Timed cycle Task execution");             }         }, 1000, 3000, timeunit.milliseconds);         //   off execution of timing and cycle tasks         thread.sleep (1000 * 10);       &Nbsp; schedule.shutdown ();         system.out.println ("pool  Shutdown: " + schedule.isshutdown ());        while  (! Schedule.isterminated ())  {             Schedule.awaittermination (1, timeunit.seconds);        }     }}


Execution of timed tasks

To say timed tasks, in fact, are used to delay tasks and periodic tasks to achieve timing.

For example, I want to start a scheduled task at 12 o'clock noon every day, based on the current program's startup time to calculate how long the delay to perform this task, and is the execution of the cycle, there is a fixed algorithm to calculate the length of the delay.

package com.usoft.schedule;import java.util.calendar;public class main23 {     private static final int period = 1000 * 60; // Seconds     private static final int one_day_millseconds = 24  * 60 * 60 * 1000;    public static void main ( String args[])  {        int dayOfHour = 0;  // 24h          int minute = 0;         int second = 0;         long delay;  //delay of the first execution of a task         calendar  c = calendar.getinstance ();        long  Currenttime = c.gettimeinmillIs ();         c.set (Calendar.hour_of_day, dayofhour);         c.set (Calendar.minute, minute);         c.set (Calendar.second, second);        long  Executetime = c.gettimeinmillis ();        delay =  executetime - currenttime < 0 ?  (executetime - currenttime +  one_day_millseconds)             :  ( Executetime - currenttime);         system.out.println (" delaytimeinmillis = " + delay);         System.out.println ("delaytimeinsecond ="  + delay / 1000);         system.out.println ("DelayTimeinhour = " + delay /  (1000 * 60 * 60));     }}

It is simple to specify the hour minute and the second, and it is said that the task will be performed at this time of the cycle. Then how long is the delay to perform this task can be calculated according to the above code.

You can also choose to perform tasks that are not periodic, but perform a task at this time.

====================end====================

Java Implementation Timer Scheduledthreadpoolexecutor

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.