Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method on specific time in java?

Tags:

java

Is it possible to call a method in java at specific time? For example of I have a piece of code like this:

class Test{      public static void main(String args[]) {         // here i want to call foo at : 2012-07-06 13:05:45 for instance         foo();     } } 

How this can be done in java?

like image 362
Sami Avatar asked Jul 06 '12 11:07

Sami


People also ask

How do you call a specific time in Java?

getTime(); Timer _timer = new Timer(); _timer. schedule(foo, alarmTime); Refer these links: Timer.

Is there a time function in Java?

The time functions can be accessed from the java. util. Date class. This represents an instance of time with millisecond precision.


2 Answers

Using a java.util.Timer class you can create a timer and schedule it to run at specific time.

Below is the example:

//The task which you want to execute private static class MyTimeTask extends TimerTask {      public void run()     {         //write your code here     } }  public static void main(String[] args) {      //the Date and time at which you want to execute     DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     Date date = dateFormatter .parse("2012-07-06 13:05:45");      //Now create the time and schedule it     Timer timer = new Timer();      //Use this if you want to execute it once     timer.schedule(new MyTimeTask(), date);      //Use this if you want to execute it repeatedly     //int period = 10000;//10secs     //timer.schedule(new MyTimeTask(), date, period ); } 
like image 72
Ramesh PVK Avatar answered Sep 28 '22 13:09

Ramesh PVK


You can use a ScheduledExecutorService, which is "a more versatile replacement for the Timer/TimerTask combination" (according to Timer's javadoc):

long delay = ChronoUnit.MILLIS.between(LocalTime.now(), LocalTime.of(13, 5, 45)); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(task, delay, TimeUnit.MILLISECONDS); 
like image 45
assylias Avatar answered Sep 28 '22 11:09

assylias