This article mainly shares an example code about ScheduledExecutorService task timing, as follows:
Sample code
package com.effective.common.concurrent.execute;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");private static DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");private static ScheduledExecutorService excutor = Executors.newSingleThreadScheduledExecutor();/** * Execute a task according to the specified frequency period<br> * The initialization delay starts execution by 0ms, and the task is re-executes every 5ms. */public void fixedRate(){excutor.scheduleAtFixedRate(new EchoServer(), //Execution thread 0, //Initialization delay 5000, //Minimum time interval between two executions starting TimeUnit.MILLISECONDS //Time unit);}/** * */public void fixDelay(){excutor.scheduleWithFixedDelay(new EchoServer(), //Execution thread 0, //Initialization delay 5000, //TimeUnit.MILLISECONDS);}/** * Execute once every day at 8 pm*/public void dayOfDelay(String time){ScheduledExecutorService executor = Executors.newScheduledThreadPool(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 a 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();}}Summarize
The above is the entire content of this article about the ScheduledExecutorService task timing code example. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!