Java scheduled task scheduledthreadpoolexecutor

Source: Internet
Author: User

Previously, the timer task used the Timer class, and later found thatScheduledthreadpoolexecutorMore powerful functions. Let's take a look at a simple example and then look at the descriptions in the API:

This scheduled task is used in my project to check the online status of the device every five minutes.

Public class checkdevicestateexcuter {Private Static final log = logfactory. getlog (checkdevicestateexcuter. class); Private Static final scheduledexecutorservice schedors = executors. newscheduledthreadpool (1); Private Static devicedao = new devicedaoimpl (); Private Static list <devicedto> devices = new arraylist <devicedto> (); // invoke DLL method to get the details of devicestatic joymindc Ommdlllib instance = joymindcommdlllib. instance; // check statespublic static void checkstart () {final runnable checker = new runnable () {public void run () {system. out. println ("check"); devices = devicedao. querydevices (); For (devicedto device: devices) {string IP = device. getip (); string id = "auto_refresh _" + IP; string inipath = xmloperationtool. playlist_tempfile_folder + ID + ". ini "; int flag = instan CE. getsysinfo (IP, inipath); If (flag = 1) {// get ini filesysteminfodto info = NULL; try {info = fileoperationtool. parseini (inipath); device. setmacadd (info. getmacaddress (); device. setip (info. getip (); device. setgateway (info. getgateway (); device. setonlinestate ("online"); device. setboottime (info. getboottime (); device. setdeviceversion (info. getversion (); device. setavailablespace (info. getfreedisk (); device. setpn O (info. getpno (); device. setwidth (info. getwidth (); device. setheight (info. getheight (); device. setstorage (info. getstorage (); device. settime (info. gettime (); device. setprgtotal (info. getprgtotal (); device. setprgindex (info. getprgindex (); device. setstatusno (info. getstatus (); If (info. getstorage (). equals ("1") {Device. setstoragename ("flash storage");} If (info. getstorage (). equals ("2") {Device. setstoragename ("Ram Store ");} If (info. getstorage (). equals ("3") {Device. setstoragename ("SD card storage");} device. setcurrentplaylist (""); device. setcurrenttemplate (""); device. setlastcommunicatetime (""); device. setcurrenttransferfilename (""); device. setcurrenttransferspeed (""); device. setcurrentpercentage (""); device. setvolume (""); device. setautoboottime (""); device. setautoshutdowntime (""); device. setplayingvideo (""); device. setprogramupda Tetime (""); device. setprogramupdatestate ("");} catch (ioexception E1) {If (log. iserrorenabled () {log. error (e1.getmessage ();} e1.printstacktrace ();} Boolean addflag = devicedao. updatedevice (device); If (addflag) {If (log. isdebugenabled () {log. debug ("Auto Update Device" + device. getname () + "successfully") ;}} else {If (log. iserrorenabled () {log. error ("Auto Update Device failed !!! ") ;}} Else {devicedao. updatedevice (IP, "offline"); If (log. isdebugenabled () {log. debug ("Auto Update Device" + device. getname () + "statue offline") ;}}}; // The checker here is a thread. 1 indicates that the thread starts to run with a delay of one unit, run the command once every 5 minutes. The unit is minute final scheduledfuture <?> Checkerhandle = scheduler. scheduleatfixedrate (checker, 1, 5, timeunit. minutes); // The note here cancels this scheduled task and stops it after 3600 days, because I check the device here, therefore, the scheduled task/* scheduler is automatically stopped unless the program exits. schedule (New runnable () {public void run () {checkerhandle. cancel (true) ;}}, 60*60, timeunit. days); */}/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub}

Let's look at the specific API information. In short, this is a very practical class.

public class ScheduledThreadPoolExecutor
Extends threadpoolexecutor
Implements scheduledexecutorservice

ThreadPoolExecutorIt can be scheduled to run commands after a given delay, or regularly run commands. When multiple auxiliary threads are requiredThreadPoolExecutor
This class is superior
Timer.

A delayed task is executed once it is enabled, but there is no real-time guarantee for when it is enabled or when it is executed after it is enabled. Enable tasks scheduled for the same execution time in the order of first-in-first-out (FIFO) submitted.

Although this class inherits from
ThreadPoolExecutorBut several inherited adjustment methods have no effect on this class. Especially, because it is used asCorepoolsizeThe fixed size pool of the thread and an unbounded queue, so the adjustmentMaximumpoolsizeNo effect.

Notes for expansion:This type of rewriting
AbstractExecutorServiceOfSubmitTo generate internal objects to control the delay and scheduling of each task. To retain functionality, any method that is further rewritten in the subclass must call the superclass version, which effectively disables the customization of additional tasks. However, this class provides alternative protected extension methodsDecoratetask(
RunnableAndCallableEach provides a version), which can be customized to useExecute,Submit,Schedule,ScheduleatfixedrateAnd
SchedulewithfixeddelayThe specific Task Type of the command to be executed. By default,ScheduledthreadpoolexecutorUse an extensionFutureTaskTask Type. However, you can use subclass in the following form to modify or replace this type.

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }   protected <V> RunnableScheduledFuture<V> decorateTask(                Runnable r, RunnableScheduledFuture<V> task) {       return new CustomTask<V>(r, task);   }   protected <V> RunnableScheduledFuture<V> decorateTask(                Callable<V> c, RunnableScheduledFuture<V> task) {       return new CustomTask<V>(c, task);   }   // ... add constructors, etc. } 

Start with the following versions:
1.5

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.