How to run multiple timer tasks in java that will be timed out in 20secs for example, but all of them have started at different time, but still they have run after 20 secs after created. I am planning to receive a lot of task that i need to keep for that period of time and then trigger another event once its seconds are gone.
There can be multiple task running at the same time.
I have seen http://www.quartz-scheduler.org/overview/quick-start but i want to know if there is another way to accomplish what i want.
This is one way of doing it using the java.utils package:
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
doTask();
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(){
System.out.println("Started at: " + Calendar.getInstance().getTime());
System.out.println("Perform your task here");
// Create new task
TimerTask task = new TimerTask() {
#Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
If you've used Java 8 before (or would like to use it), you could try using this code instead:
public class Main {
private static final int delayMilliseconds = 20000; // 20 seconds
private static Timer timer;
public static void main(String[] args) throws Exception{
System.out.println("START");
// Create a Timer
timer = new Timer();
doTask(() -> System.out.println("Task 1"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 2, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 3, starting a second later"));
Thread.sleep(1000);
doTask(() -> System.out.println("Task 4, starting a second later"));
Thread.sleep(1000);
System.out.println("END");
}
public static final void doTask(Runnable function) throws Exception{
System.out.println("Started at: " + Calendar.getInstance().getTime());
// Run the function here
function.run();
// Create new task
TimerTask task = new TimerTask() {
#Override
public void run() {
// Run the "timeout finished" function here.
System.out.println("Timed out! " + Calendar.getInstance().getTime());
}
};
// Schedule a task for in 20 seconds in the future.
timer.schedule(task, delayMilliseconds);
}
}
The second method makes it so you can pass a function to the doTask() function. Look at this link for more info on the Timer class and look at this link for more info on lambdas in java 8. :)
Related
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.
I am trying to execute a task periodically. For example:
class MyTimerTask implements TimerTask
{
public void run() {
// Some actions to perform
}
Timer cleaner = new Timer(true);
cleaner.scheduleAtFixedRate(new MyTimerTask(), 0, PURGE_INTERVAL);
}
However, the run method is executing only once. But if I put the first time delay as 10 seconds, then the run method doesn't execute even once.
Example:
cleaner.scheduleAtFixedRate(new MyTimerTask(), 10, PURGE_INTERVAL);
This sounds like an issue with time units to me. Ensure that you're converting to milliseconds correctly.
The easiest way to do this is to use Java's TimeUnit.
Timer cleaner = new Timer(true);
cleaner.scheduleAtFixedRate(new MyTimerTask(),
TimeUnit.SECONDS.toMillis(10),
TimeUnit.SECONDS.toMillis(30));
It could also be caused by the Timer being started in daemon mode. If all your main method does is set up the timer and then return the timer will never execute since it's the last remaining thread and because it's a daemon thread the JVM will exit.
To fix this either make the timer thread not a daemon (i.e. pass false in the constructor) or make the main thread wait for user input before exiting.
Here's an example using both of the above:
public class TimerDemo extends TimerTask {
public void run() {
System.out.printf("Time is now %s%n", LocalTime.now());
}
public static void main(String[] args) throws IOException {
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(new TimerDemo(),
TimeUnit.SECONDS.toMillis(5),
TimeUnit.SECONDS.toMillis(10));
System.out.printf("Program started at %s%n", LocalTime.now());
System.out.println("Press enter to exit");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
// Wait for user to press enter
reader.readLine();
}
System.out.println("Bye!");
}
}
And output of running it:
Program started at 14:49:42.207
Press enter to exit
Time is now 14:49:46.800
Time is now 14:49:56.799
Time is now 14:50:06.799
Time is now 14:50:16.799
Time is now 14:50:26.799
[I pressed 'enter']
Bye!
Process finished with exit code 0
I had a hard time figuring out exactly what is your problem, so this might not be exactly what you are asking for, but this solution might fit you:
public class MyTimerTask implements Runnable {
private static final TimeUnit timeUnit = TimeUnit.SECONDS;
private final ScheduledExecutorService scheduler;
private final int period = 10;
public static void main(String[] args) {
new MyTimerTask();
}
public MyTimerTask() {
scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(this, period, period, timeUnit);
}
#Override
public void run() {
// This will run every 10 seconds
System.out.println("Ran...");
}
}
I have a thread in Java that makes a web call and stores the information retrieved, but it only retrieves information for that particular instant. I'd like to run this thread every second for a certain period of time to get a better view of the data. How can I do this? I've looked at ScheduledExecutorService, and from what I can tell if the thread is still running when it's time to set up the next run, it waits until the first thread is complete, which isn't what I'm looking for.
You can do this by a double schedule. Use scheduleWithFixedDelay() to set off a job every second. This job starts the method which you really want to run. Here is some code based on Oracle's ScheduledExecutorService API.
The Thread.sleep() is there to simulate a long-running task.
class Beeper {
public static void main(String[] args) {
(new Beeper()).beep();
}
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beep() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
final Runnable beeper2 = new Runnable() {
public void run() {
(new Thread(beeper)).start();
}
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper2, 1, 1, SECONDS);
}
}
What you need is the scheduleAtFixedRate method: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)
When the scheduler waits until the first thread is complete, it's because you're using scheduleWithFixedDelay.
However, if you absolutely want the threads run concurrently, you should try this:
pool.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
pool.submit(myJob);
}
}, 1, 1, TimeUnit.SECONDS);
I advise to always use a pool.
What about this?
public static void main (String [] args) throws InterruptedException{
ExecutorService executorService =
Executors.newFixedThreadPool(10);
while (true){
executorService.submit(new Runnable() {
#Override
public void run() {
// do your work here..
System.out.println("Executed!");
}});
Thread.sleep(1000);
}
}
I have some type of task for example in a loop with same method but different arguments,
I need to execute these tasks in one after another in some intervals,
and all this activity need to be execute in again and again in a particular schedule,
e.g. let say I have a method called
public void GetData(String tablename){
}
so first time I will provide table1 then table2 then table3.....
similar to for loop but need some interval in between,
and same above all execution need to execute in each 10 min,
sample code I have implemented as
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable runner = new Runnable() {
public void run() {
getData(String table);
}
};
final ScheduledFuture<?> taskHandle =
scheduler.scheduleAtFixedRate(runner, 1, 10, SECONDS);
its working fine for one table for need help and best way to implement for multiple tables.
tryjava.util.Timer to schedule a task to execute
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
You can just use Thread.sleep() in your loop (if it's not on the main thread). Something like this (the code is not tested so may contain errors):
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
public void run() {
getData(String table);
}
Thread.sleep(10000);
}
Is there any way to write a program in java, so that its main method schedule (or at a 10-15 min interval) another method to executes it at a particular interval?
You can use Job scheduler for this. i.e.
Quartz Job Scheduler.
Refer this Quartz API
Or
You can use ScheduledExecutorService Java Interface
Refer this Documentation
I think you are looking for the Time class.
See Timer Class API
You can use this class like:
You want to perform a Method every 600 miliseconds. You write:
ActionListener taskPerformer = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//Do your stuff
}
};
Timer t = new Timer(600, taskPerfomer);
t.start;
There are more options. This example will be executed once but it can be executed in an interval.
I hope it helps.
Use Scheduled Thread pool executor:
Schedual your worker thread to execute at every 10 Seconds
scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
1) Class WorkerThread .java
public class WorkerThread implements Runnable{
private String command;
public WorkerThread(String s){
this.command=s;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date());
processCommand();
System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date());
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public String toString(){
return this.command;
}
}
2) Class ScheduledThreadPool .java
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledThreadPool {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
//schedule to run after sometime
System.out.println("Current Time = "+new Date());
for(int i=0; i<3; i++){
Thread.sleep(1000);
WorkerThread worker = new WorkerThread("do heavy processing");
scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
}
//add some delay to let some threads spawn by scheduler
Thread.sleep(30000);
scheduledThreadPool.shutdown();
while(!scheduledThreadPool.isTerminated()){
//wait for all tasks to finish
}
System.out.println("Finished all threads");
}
}
If your task is not so big, you can use Thread.sleep() method(example 10 iteration with 10 minutes delay):
public static void main(String[] args) throws InterruptedException {
methodOne();
for (int i = 0; i < 10; i++) {
Thread.sleep(600000);
methodTwo();
}
}