How to call a method on specific time in java?
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 );
}
How to fire a method at a specific time with Java?
There's no listener that checks periodically in Java unless you make one yourself. To schedule something to occur at a particular time you typically delay execution by the difference in time between now and the desired time. You can do this quite nicely with Java 8's date/time API. If you want something to trigger at 9pm today, I suggest:
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime ninePMToday = LocalDateTime.now()
.withHour(21)
.withMinute(0)
.withSecond(0)
.withNano(0);
final ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.schedule(() -> System.out.println("It's 9pm!"),
now.until(ninePMToday, ChronoUnit.MILLIS),
TimeUnit.MILLISECONDS);
You can also schedule it to repeatedly execute at 9pm every day with a small tweak to the scheduler call:
ses.scheduleAtFixedRate(() -> System.out.println("It's 9pm!"),
now.until(ninePMToday, ChronoUnit.MILLIS),
TimeUnit.DAYS.toMillis(1),
TimeUnit.MILLISECONDS);
Change the code above to adjust for your 60 second interval (check the documentation for the scheduler methods for more information).
How do I time a method's execution in Java?
There is always the old-fashioned way:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
Run a java function after a specific number of seconds
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
EDIT:
javadoc says:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.
How to run a specific method on a specific date and time?
There are multiple java scheduler frameworks available to do the tasks at your specified time, interval, periodicity. Apache quartz is one of the commonly used ones.
or simply make use of java ScheduledExecutorService
How Would I Execute an Event at a Specific Time
I suggest you use a ScheduledExecutorService
.
ScheduledExecutorService scheduledActivity = Executors.newScheduledThreadPool(1);
scheduledActivity.scheduleAtFixedRate(() -> {
//whatever you want to do at 11 PM on Thursday
},
initialDelay, //you have to calculate an initial delay
TimeUnit.DAYS.toSeconds(7), //makes it run every 7 days
TimeUnit.SECONDS);
The initalDelay
is always the difference between the current time and the time you want your service to run (11 PM on Thursday in your case).
There are several solutions on how to achieve this, but I personally prefer the following approach:
//you might want to change the timezone to your liking
LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Berlin"));
LocalDateTime then = LocalDateTime.now(ZoneId.of("Europe/Berlin"));
//then equals the next or current Thursday on 13:00 (or 1 PM)
then = then.with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY)).withHour(13).withMinute(0).withSecond(0);
Duration duration = Duration.between(now, then);
long initialDelay = duration.getSeconds();
//initialDelay can become negative if the current day is Thursday but it's already too late
if (initialDelay < 0) {
//add one week to shift the delay to the next correct time
initialDelay = Duration.between(now, localDate.with(TemporalAdjusters.next(DayOfWeek.THURSDAY)).withHour(13).withMinute(0).).getSeconds();
}
(This definitely can be optimized!)
Related Topics
How to Merge Documents Correctly
Differencebetween Optional.Flatmap and Optional.Map
How to Set Connection Timeout with Okhttp
How to Get a List from Some Class Properties with Java 8 Stream
How to Deal with Maven-3 Timestamped Snapshots Efficiently
How to Efficiently Remove All Null Elements from a Arraylist or String Array
Receiving "Wrong Name" Noclassdeffounderror When Executing a Java Program from the Command-Line
Character Encoding Detection Algorithm
Java Equivalent of Unsigned Long Long
Execute Jsp Directly from Java
Parsing PDF Files (Especially with Tables) with PDFbox
Java String.Indexof and Empty Strings
JSON - Iterate Through JSONarray
Numeric Textfield for Integers in Javafx 8 with Textformatter And/Or Unaryoperator
What Does an Integer That Has Zero in Front of It Mean and How to Print It