Planning a java process for a specific time interval with a given delay

We want to schedule a Java process to run before a certain time interval. I am currently thinking of using TimerTask to plan this process. At the beginning of each cycle, the current time is checked, and then compared with the set time and the process stops if the time is up. Our code looks something like this:

 import java.util.Timer; import java.util.TimerTask; public class Scheduler extends TimerTask{ public void run(){ //compare with a given time, with getCurrentTime , and do a System.exit(0); System.out.println("Output"); } public static void main(String[] args) { Scheduler scheduler = new Scheduler(); Timer timer = new Timer(); timer.scheduleAtFixedRate(scheduler, 0, 1000); } } 

Is there a better approach for this?

+6
source share
2 answers

Instead of checking whether the deadline has been reached in each individual iteration, you can schedule another task for the specified deadline and cancel the call on your timer.

Depending on the complexity, you might consider using a ScheduledExecutorService, such as ScheduledThreadPoolExecutor. See in this answer when and why.

A simple working example with a timer:

 public class App { public static void main(String[] args) { final Timer timer = new Timer(); Timer stopTaskTimer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { System.out.println("Output"); } }; TimerTask stopTask = new TimerTask() { @Override public void run() { timer.cancel(); } }; //schedule your repetitive task timer.scheduleAtFixedRate(task, 0, 1000); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse("2015-06-09 14:06:30"); //schedule when to stop it stopTaskTimer.schedule(stopTask, date); } catch (ParseException e) { e.printStackTrace(); } } } 
+3
source

You can use RxJava , a very powerful library for reactive programming.

 Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS); t.subscribe(new Action1() { @Override public void call(Object o) { System.out.println("Hi "+o); } } ) ; try { Thread.sleep(10000); }catch(Exception e){ } 

You can even use lambda syntax:

 Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS); t.forEach(it -> System.out.println("Hi " + it)); try { Thread.sleep(10000); }catch(Exception e){ } 
+2
source

Source: https://habr.com/ru/post/988778/


All Articles