How do I schedule a task to run at periodic intervals?
Use timer.scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
- task - task to be scheduled.
- delay - delay in milliseconds before task is to be executed.
- period - time in milliseconds between successive task executions.
Throws:
- IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
- IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
How do I schedule a task to run at very long periodic intervals
yes its my mistake.
I was calculating repeat period in wrong way.
(7 * 24 * 60 * 60 * 1000) * 5 results in negative value.
After typecasting the answer to long it works fine.
(long)5 * 7 * 24 * 60 * 60 * 1000 gives correct value.
Thanks.
How do I schedule a task to run once?
While the java.util.Timer
used to be a good way to schedule future tasks, it is now preferable1 to instead use the classes in the java.util.concurrent
package.
There is a ScheduledExecutorService
that is designed specifically to run a command after a delay (or to execute them periodically, but that's not relevant to this question).
It has a schedule(Runnable, long, TimeUnit)
method that
Creates and executes a one-shot action that becomes enabled after the given delay.
Using a ScheduledExecutorService
you could re-write your program like this:
import java.util.concurrent.*;
public class Scratch {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
System.out.println("Starting one-minute countdown now...");
ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
@Override
public void run() {
// do the thing
System.out.println("Out of time!");
}}, 1, TimeUnit.MINUTES);
while (!countdown.isDone()) {
try {
Thread.sleep(1000);
System.out.println("do other stuff here");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
scheduler.shutdown();
}
}
One of the nice things you get by doing things this way is the ScheduledFuture<?>
object you get back from calling schedule()
.
This allows you to get rid of the extra boolean
variable, and just check directly whether the job has run.
You can also cancel the scheduled task if you don't want to wait anymore by calling its cancel()
method.
1See Java Timer vs ExecutorService? for reasons to avoid using a Timer
in favor of an ExecutorService
.
How to schedule a periodic task in Java?
Use a ScheduledExecutorService:
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
Java: Running task at different intervals
You can scedule task execution at 1sec rate and make the task itself to skip unwanted times
How to schedule job with a particular time as well as interval?
You can convert the inner schedule (every 4 hours) into a separate function which would be called by the main schedule (fixed time). The inner schedule function would be the one calling your job function.
Example -
import schedule
import time
def job():
print "I am working" #your job function
def schedule_every_four_hours():
job() #for the first job to run
schedule.every(4).hour.do(job)
return schedule.CancelJob
schedule.every().day.at("09:00").do(schedule_every_four_hours)
while True:
schedule.run_pending()
time.sleep(1)
If you would like to kill the schedule based on your requirement read more here. Check here.
How to schedule a function to run every hour on Flask?
You can use BackgroundScheduler()
from APScheduler package (v3.5.3):
import time
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=60)
scheduler.start()
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.
Related Topics
Issue Using Imageio.Write Jpg File: Pink Background
Should I Declare Jackson's Objectmapper as a Static Field
Why Do We Need Immutable Class
Package Conflicts with Automatic Modules in Java 9
Capturing Image from Webcam in Java
Java: Method to Get Position of a Match in a String
Deserializing Polymorphic Types with Jackson Based on the Presence of a Unique Property
Is Java.Util.Date Using Timezone
Log4J: Log Output of a Specific Class to a Specific Appender