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);
}
Related
I need to execute a certain task periodically within a certain timeout.
But dependent on the result of the task, I want to stop before the end of the timeout is reached. And in addition I need a reference to the currently executed task in order to have the chance to ask for the result.
Solution to 1) is no problem, because it can be solved with the little code snipped shown below. But I can not figure out how to integrate 2). So with this code example, I would like that the beeper object runs code which can have a positive or a negative result and based on (for example) a positive result, the beeper task should no longer be executed periodically.
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In your run method if condition is fulfilled then invoke scheduler.shutdown(). That should do exactly what you want.
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
if(isMyCondition() {
scheduler.shutdown();
}
}
};
See javadoc for ExecutorService.shutdown()
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. :)
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 want to create 10 Timer.scheduler inside the run method, so i used for loop but its executing only once. not repeatedly calling the scheduler in this loop.
Please check my code below,
public void run()
{
for(int i=0;i<10;i++)
{
timer.schedule(task, 10000);
}
}
In this code I created 10 schedulers using for for loop but it executing only once. And how to differentiate each Scheduler
Please help me,
Assuming you're using java.util.Timer then possibly the reason why it's only running the task once is because a java.util.TimerTask can only be scheduled once. This code will run the first scheduled task but will fail with an java.lang.IllegalStateException: Task already scheduled or cancelled there after.
To differentiate each scheduled task you could do something like this. Each scheduled NamedTimerTask will have its own name. You can choose to modify this to add whatever you need to identify your scheduled tasks.
public static void main(String[] args) {
Timer timer = new Timer();
for (int i = 0; i < 10; i++) {
timer.schedule(new NamedTimerTask("task" + i) {
#Override
public void run() {
System.out.println(name);
}
}, 1000);
}
}
static abstract class NamedTimerTask extends TimerTask {
final String name;
NamedTimerTask(String name) {
this.name = name;
}
}
HI
I want to run a method in my program evry X hours, how to do that ?
Im googling and there is nothing :/
You could consider Quartz.
It is some sort of cron that runs inside java. I admit though that it is probably an overkill if you want to schedule only one job.
You could take a look at the Timer class, but the best option is to use a ScheduledExecutorService:
e.g. This will beep at a scheduled rate:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}
I use the Quartz framework for most of my scheduling ( http://www.quartz-scheduler.org/ ) but if you're doing something simple, java.util.Timer is fine.
// in a class body...
public static void main( String[] argv ) {
Timer timer = new Timer();
int secondsBetweenRuns = 3600;
timer.schedule( new MyOwnTask(), 0, secondsBetweenRuns * 1000 );
}
static class MyOwnTask extends TimerTask {
public void run() {
doWhateverYouNeedToDoEveryHour();
}
}
Scheduled Task (in Windows) or Cron (in Unix)
You could save the time at a certain point, than start a timer. When the time is up, you run the method and restart the timer.