Run a job for every one hour in java thread - java

I have to run a job using a thread for every 1 hour. This job is to read files in a folder. I have created a simple thread
Thread t = new Thread() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
which runs every one hour so that I can call the function to read the files. I want to know if this approach is good or any other approach is good

You can use ScheduledExecutorService for this task, and here is a Sample Example

If you want to use just Thread then try
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
otherwise its a good choice that you can go with ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);

import java.util.Timer;
import java.util.TimerTask;
public class MyTimer {
public static void main(String[] args) {
OneHourJob hourJob = new OneHourJob();
Timer timer = new Timer();
timer.scheduleAtFixedRate(hourJob, 0, 5000 * 60 * 60); // this code
// runs every 5 seconds to make it one hour use this value 5000 * 60 *
// 60
}
}
class OneHourJob extends TimerTask {
#Override
public void run() {
System.out.println("Ran after one hour.");
}
}
Above code runs every five seconds. Whatever work you need to do write that code in run method of OneHourJob

Related

Using ScheduledExecutorService, How to Start a Thread without waiting for other thread to complete at fixed interval?

I want to run a task at every particular interval of time regardless of completion of previous thread. And I've used ScheduledExecutorService with the schedule time at every one second. But the problem is, in my Runnable, If I make thread to sleep for 5 seconds, My ScheduledExecuterService also getting executed in every 5 seconds while it supposed to run each thread at 1 second.
It seems like it ScheduledExecuterService is waiting for previous thread to completion. But I want, The task to be triggered at every 1 second no matter what if job inside the task waits for longer time.
Here's is my code.
public class MyTask implements Runnable {
public void run() {
System.out.println("hi there at: "+ new java.util.Date());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And here's my ScheduledExecutorService Code.
public class JavaScheduledExecutorServiceExample {
public static void main(String[] args) {
ScheduledExecutorService execService = Executors.newScheduledThreadPool(5);
execService.scheduleAtFixedRate(new MyTask(), 0, 1000, TimeUnit.MILLISECONDS);
}
}
Correct me If I'm doing something wrong. And If I'm wrong, is there any alternative to achieve the same? Providing Any best practices could be more helpful :)
"If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute." The behavior you are seeing is consistent with the javadocs
I believe this will perform the way you specified:
public class JavaScheduledExecutorServiceExample {
private static ScheduledExecutorService execService = null;
private static int timesAsleep = 0;
public static class MyTask implements Runnable {
public void run() {
System.out.println("hi there at: "+ new java.util.Date());
// schedule again
execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
try {
int i = timesAsleep;
timesAsleep++;
System.out.println("asleep " + i + "----------------------");
Thread.sleep(5000);
System.out.println("awoke " + i + "----------------------");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
execService = Executors.newScheduledThreadPool(5);
execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
}
}
Notice the use schedule() instead of scheduleAtFixedRate() on the ScheduledExecutorService instance. It also schedules the next task as soon as it starts the new task.

Delayed while loop

I need a loop with delay (like a timer) but have problems with the end of it, this is my code:
while(true) {
if (someValue == 10) {
break;
}
//Wait two seconds. <-----
}
System.out.println("While Ended.");
This works fine, but need to be repeated every 2 seconds. I tried with Timer but the "While Ended." message is shown before of the timer end. How can i solve this problem?
I need that this process not freeze the thread. (like while loop).
Precision is not necessary.
You can put Thread.sleep in a while-loop to sleep for a number of seconds. This solution has problems, e.g. it blocks the thread, breaks on interrupts, etc.
Better is to use a ScheduledThreadPoolExecutor and use the schedule method to schedule the task to run every so many seconds. This is correct but you should have some knowledge of how multithreaded programs work or you'll make mistakes and create subtle bugs.
When you need something like a timer than you could use a timer:
import java.util.Timer;
import java.util.TimerTask;
public class TTimer extends TimerTask {
private static Timer timer;
#Override
public void run() {
System.out.println("timer");
}
public void stop() {
timer.cancel();
timer.purge();
this.cancel();
}
public TTimer( long interval) {
timer = new Timer(true);
timer.scheduleAtFixedRate(this, 0, interval);
}
public static void main(String[] args) {
TTimer t = new TTimer(2000);
while( true ) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
}
Place your code in the run() method, check your condition (somevalue == 10) and call the stop method to shut the timer down.

Java: Scheduling a task in random intervals

I am quite new to Java and I'm trying to generate a task that will run every 5 to 10 seconds, so at any interval in the area between 5 to 10, including 10.
I tried several things but nothing is working so far. My latest effort is below:
timer= new Timer();
Random generator = new Random();
int interval;
//The task will run after 10 seconds for the first time:
timer.schedule(task, 10000);
//Wait for the first execution of the task to finish:
try {
sleep(10000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
//Afterwards, run it every 5 to 10 seconds, until a condition becomes true:
while(!some_condition)){
interval = (generator.nextInt(6)+5)*1000;
timer.schedule(task,interval);
try {
sleep(interval);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
"task" is a TimerTask. What I get is:
Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled
I understand from here that a TimerTask cannot be reused, but I am not sure how to fix it. By the way the my TimerTask is quite elaborate and lasts itself at least 1,5 seconds.
Any help will be really appreciated, thanks!
try
public class Test1 {
static Timer timer = new Timer();
static class Task extends TimerTask {
#Override
public void run() {
int delay = (5 + new Random().nextInt(5)) * 1000;
timer.schedule(new Task(), delay);
System.out.println(new Date());
}
}
public static void main(String[] args) throws Exception {
new Task().run();
}
}
Create a new Timer for each task instead, like you already do: timer= new Timer();
And if you want to synchronize your code with your threaded tasks, use semaphores and not sleep(10000). This might work if you're lucky, but it's definitely wrong because you cannot be sure your task has actually finished.

Why does this java timer sample never end

I was looking for a Java timer sample and found the code below at
http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.html
But if you run the sample, although it does print Timer stops now... it does not return to the command prompt. This is at least what is happening on my Windows XP machine using cmd.exe.
Why does it not return control to the prompt in this case?
import java.util.Timer;
import java.util.TimerTask;
public class TimerSample {
public static void main(String[] args) {
//1- Taking an instance of Timer class.
Timer timer = new Timer("Printer");
//2- Taking an instance of class contains your repeated method.
MyTask t = new MyTask();
//TimerTask is a class implements Runnable interface so
//You have to override run method with your certain code black
//Second Parameter is the specified the Starting Time for your timer in
//MilliSeconds or Date
//Third Parameter is the specified the Period between consecutive
//calling for the method.
timer.schedule(t, 0, 2000);
}
}
class MyTask extends TimerTask {
//times member represent calling times.
private int times = 0;
public void run() {
times++;
if (times <= 5) {
System.out.println("I'm alive...");
} else {
System.out.println("Timer stops now...");
//Stop Timer.
this.cancel();
}
}
}
It does not return to your command prompt because it is not expected to do so.
Timer creates single non-deamon thread to run all tasks. It does not terminate the thread unless you ask it. When you execture task.cancel() method you just cancel the current task, not the whole timer which is still alive and is ready to do something else.
To terminate timer you should call its stop() method, i.e. timer.stop();
In a real program you would keep a copy of the timer object and when eg program is to be closed down do a timer.cancel().
For this simple example, I added the code below after timer.schedule(t, 0, 2000);
try {
Thread.sleep(20000);
} catch(InterruptedException ex) {
System.out.println("caught " + ex.getMessage());
}
timer.cancel();
}
You need to explicitly terminate the Timer using timer.cancel(), e.g.:
class MyTask extends TimerTask {
private int times = 0;
private Timer timer;
public MyTask(Timer timer) {
this.timer = timer;
}
public void run() {
times++;
if (times <= 5) {
System.out.println("I'm alive...");
} else {
System.out.println("Timer stops now...");
//Stop Timer.
this.cancel();
this.timer.cancel();
}
}
}

Synchronize two timers with multiple instances (Java)

I'm a newbie in Java and I haven't work with threads in past. Now I have a really tricky issue for my level of knowledge.
I have developed two functionalities the "Send mail" and the "Check mail". Each user register his preferences and the system creates two catalogues with many instructions for periodic work like
A) send message every 1500 msec
B) send message every 1800 msec
C) send message every 3000 msec
And
A) check message every 2000 msec
B) check message every 6000 msec
C) check message every 8000 msec
I tried many ways with threads but I fail to do it work.
My question is which is the best way to synchronize them? Below is code from my last effort using threads.
public class MailCreatorThread extends Thread {
#Override
public void run() {
CreateMail(_date); //creates a mail with _date as subject
}
}
public class GPSThread extends Thread {
#Override
public void run() {
// TODO Auto-generated method stub
while (!_isTimeToStop) {
try {
while (_servicesToUpdate.size() == 0) {
Thread.sleep(500);
}
_currentService = (MyService) _servicesToUpdate.get(0)
.clone();
_servicesToUpdate.remove(0);
MailCreatorThread mailCreatorThread = new MailCreatorThread();
mailCreatorThread.start();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class CheckServicesThread extends Thread {
#Override
public void run() {
// TODO Auto-generated method stub
while (!_isTimeToStop) {
try {
Thread.sleep(1000);
for (int j = 0; j < _servicesList.length; j++) {
MyService currentService = ((MyService) _servicesList[j]);
if (myService.getTimeToNextUpdate() - 1000 <= 0) {
_servicesToUpdate
.add((MyService) currentService
.clone());
currentService
.setTimeToNextUpdate(currentService
.getUpdatePeriod());
} else {
currentService
.setTimeToNextUpdate(currentService
.getTimeToNextUpdate() - 1000);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
stopSelf();
}
}
You can use a ScheduledExecutorService to run thos periodic tasks. The syntax is fairly straightforward:
Runnable check = new Runnable() {
public void run() {
checkMessage();
}
}
Runnable send = new Runnable() {
public void run() {
sendMessage();
}
}
//since what you are doing is mostly I/O you probably want to have
//more than one thread available so that if one operation blocks,
//the other ones can be launched in parallel
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
scheduler.scheduleAtFixedRate(check, 0, 1500, MILLISECONDS);
scheduler.scheduleAtFixedRate(send, 0, 6000, MILLISECONDS);
Note: Timer mentioned in Ozzy's answer should not be used any more as it has been improved in Java 1.5 by ScheduledThreadPoolExecutor, as explained in Timer's javadoc :
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
In java you have built-in Timer and TimerTask classes to help you repeat a task in a separate thread.
This will create a Timer which will create its own background Thread:
Timer t = new Timer();
You can then schedule as many tasks as you want to that timer, they will share the timer's own thread.
This is how you can schedule a single task on the timer thread, after a delay of 2000ms = 2s:
t.schedule(new TimerTask() {
#Override
public void run() {
//task to perform
}
}, 2000);
This is how you can schedule a repeated task on the timer thread, after a delay of 1s, and repeat the task at 1.5s intervals:
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//task to perform every 1.5 seconds
}
}, 1000, 1500);
Now you have a choice to schedule both tasks (checkMail, sendMail) to the same Timer (same thread) or give them each their own Timer (separate threads).
For more info, refer to the java docs (http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html)
Hope this helps.

Categories