Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule a periodic task in Java?

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?

I'm currently using java.util.Timer.scheduleAtFixedRate. Does java.util.Timer.scheduleAtFixedRate support long time intervals?

like image 951
Ariyan Avatar asked Oct 18 '11 21:10

Ariyan


People also ask

How do you schedule an event in Java?

Use the builtin java. util. Timer class to schedule code to run at a given future time or after a given delay.

What is task scheduling in Java?

Java programming language provides a class utility known as Timer Task. It allows one to schedule different tasks. In other words, a task can be executed after a given period or at a specified date and time. A Timer in Java is a process that enables threads to schedule tasks for later execution.


1 Answers

Use a ScheduledExecutorService:

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);  scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS); 
like image 76
b_erb Avatar answered Sep 19 '22 11:09

b_erb