Sample Code for scheduled ScheduledExecutorService tasks,
This article mainly shares an instance code about the scheduled ScheduledExecutorService task, as follows:
Sample Code
Package com.paitive.common.concurrent.exe cute; import java. text. dateFormat; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; public class Schedule {private static DateFormat dateFormat = new SimpleDateFormat ("yy-MM-dd HH: mm: ss"); priva Te static DateFormat dayFormat = new SimpleDateFormat ("yy-MM-dd"); private static ScheduledExecutorService excutor = Executors. newSingleThreadScheduledExecutor ();/*** execute a task in a specified frequency period <br> * the initialization delay starts from 0 ms, and the task is re-executed every 5 ms. */Public void fixedRate () {excutor. scheduleAtFixedRate (new EchoServer (), // The execution thread is 0, // The initialization delay is 5000, // The minimum interval TimeUnit between the two executions. MILLISECONDS // time unit);}/*****/public void fixDelay () {excutor. scheduleWithFixedDelay (new EchoServer (), // The execution Thread 0, // The initialization delay is 5000, // the interval from the last execution to the next execution start TimeUnit. MILLISECONDS);}/*** run once every night */public void dayOfDelay (String time) {ScheduledExecutorService executor = Executors. newSchedul EdThreadPool (1); long oneDay = 24*60*60*1000; long initDelay = getTimeMillis ("20:00:00")-System. currentTimeMillis (); initDelay = initDelay> 0? InitDelay: oneDay + initDelay; executor. scheduleAtFixedRate (new EchoServer (), initDelay, oneDay, TimeUnit. MILLISECONDS);}/*** get the number of MILLISECONDS corresponding to the given time * @ param string "HH: mm: ss" * @ return */private static long getTimeMillis (String time) {try {Date currentDate = dateFormat. parse (dayFormat. format (new Date () + "" + time); return currentDate. getTime ();} catch (ParseException e) {e. printStackTrace ();} return 0;} public static void main (String [] args) {Schedule schedule = new Schedule (); schedule. fixedRate (); schedule. fixDelay ();}}
Summary
The above is all the sample code for the scheduled ScheduledExecutorService task in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!