Java scheduled task ScheduledThreadPoolExecutor

Source: Internet
Author: User

Previously, the Timer task used the Timer class. Later, it was found that ScheduledThreadPoolExecutor is more powerful. Let's take a look at a simple example and then look at the description in the API:


This scheduled task is used in my project to check the online status of the device every five minutes.
[Java]
Public class CheckDeviceStateExcuter {
 
Private static final Log log = LogFactory. getLog (CheckDeviceStateExcuter. class );

Private static final ScheduledExecutorService schedpool = Executors. newScheduledThreadPool (1 );
 
Private static DeviceDao deviceDao = new DeviceDaoImpl ();
Private static List <DeviceDTO> devices = new ArrayList <DeviceDTO> ();

// Invoke DLL method to get the details of device
Static JoymindCommDLLLib instance = JoymindCommDLLLib. INSTANCE;
// Check states
Public 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 = instance. GetSysInfo (ip, iniPath );

If (flag = 1 ){
// Get ini file
SystemInfoDTO 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. setpNo (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 storage ");
}
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. setProgramUpdateTime ("");
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 the startup delay. 1 unit starts to execute this thread and then runs it every 5 minutes. The unit is minute.
Final ScheduledFuture <?> CheckerHandle = schedrate. scheduleAtFixedRate (checker, 1, 5, TimeUnit. MINUTES );
 
// The note here is to cancel the scheduled task and stop it after 3600 days. Because I check the device, this scheduled task is automatically stopped unless the program exits.
/*
Schedable. 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
ThreadPoolExecutor, which can run commands after a given delay or regularly execute commands. This class is superior to Timer when multiple auxiliary threads are required or ThreadPoolExecutor is required to have additional flexibility or functionality.

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 ThreadPoolExecutor, several inherited adjustment methods do not work for this class. In particular, because it serves as a fixed-size pool that uses corePoolSize threads and an unbounded queue, adjusting maximumPoolSize has no effect.

Extension Note: This class overrides the submit method of AbstractExecutorService to 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 an alternative to the protected Extension Method decorateTask (one version for Runnable and Callable ), you can customize the task types used to run commands through execute, submit, schedule, scheduleAtFixedRate, and scheduleWithFixedDelay. By default, ScheduledThreadPoolExecutor uses a task type that extends FutureTask. 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.
}
 

Author: huxiweng

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.