Time Schedule Error - java

Please have a look at the following code
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, System.currentTimeMillis(),1000);
}
public static void main(String[]args)
{
new Test();
}
}
In here, you can see it is not printing anything! In other words, the time is not scheduled! Why is that? I want to schedule the task to happen in every second. Please help!

You are telling the Timer to wait (approximately) 1363531420 milliseconds before executing your TimerTask. This works out to ~42 years. You should be using Timer.schedule(yourTask, 0, 1000).

Try to execute this code:
import java.util.Timer;
import java.util.TimerTask;
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, 0,1000);
}
public static void main(String[]args)
{
new Test();
}
}

Take a look at the javadoc, there are two methods:
schedule(TimerTask task, Date firstTime, long period)
schedule(TimerTask task, long delay, long period)
You are passing in (TimerTask, long, long) and are therefore invoking the second one - i.e. schedule the task to run for the first time in System.currentTimeMillis() millis and every second thereafter. So your task will run for the first time at Thu Jun 01 06:45:28 BST 2056, to find that out:
public static void main(String[] args) {
System.out.println(new Date(2*System.currentTimeMillis()));
}
You need to invoke the method with zero:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("Updated");
}
}, 0, 1000);
This means schedule the task to run for the first time in zero millis and every second thereafter.

You have set the delay to the current time in millis (which would be a very long time :) ). You probably intended this:
public class Test {
public Test()
{
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run()
{
System.out.println("Updated");
}
}, new Date(System.currentTimeMillis()),1000); //<--- Notice a date is being constructed
}
public static void main(String[]args)
{
new Test();
}
}
Where you set the firstTime to the current date.

Related

Why for loop does not execute inside TmerTask

I want to repeat a for loop inside below code inside a service every some time ,but it print only one line and runs one time only
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 10000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
for (int i=0; i<10; i++){
Log.i("TAG", " inside method ");}
}
};
}
You are calling the following method.
public void schedule(TimerTask task, long delay)
So the task executes only once after delay.
If you want to execute it periodically you need to call the bellow method.(you may pass same value for delay and period)
public void schedule(TimerTask task, long delay, long period)
Your another query is it prints first line only. Most probably this is an issue with the Log. try System.out.print() instead of Log.i() to debug.
class MyTimerTask extends TimerTask {
private int counter = 1;
public void run() {
timerHandler.post(new Runnable() {
public void run() {
Toast.makeText(this, "" + counter, Toast.LENGTH_SHORT).show();
counter++;
}
});
if (counter == 10) {
myTimer.cancel();
myTimer.purge();
}
}
}
//Thats the usage like on ButtonClick
MyTimerTask myTimerTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, 500, 1000);
Do you really need to run Loop ?

Java - Reusing Timer Object after calling cancel

I have an application in Java where I need to schedule a TimerTaskwhich will be executed after 500ms , however if a certain event occurs, I must reset the timer for this task (so that we must wait another 500ms for it to execute). I have a timer declared for the whole class. I use the following code:
public static void main(String[] args) {
if (curr_pck == my_pck) {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
}
}
public static void myTask() {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
//EXECUTE CODE WHICH ISN'T RELEVANT TO THE QUESTION
}
I know that if I use timer.cancel() I can't reuse the timer object, however I thought reinitialising it in the line timer = new Timer() should solve this issue. Is there any way around this?
EXCEPTION on line timer.schedule(new TimerTask() { inside myTask() function:
java.lang.IllegalStateException: Timer already cancelled.
Create a class Timerr with the appropriate methods. Then access it as if it were a normal timer.
public class Timerr
{
private Timer timer;
public Timerr()
{
timer = new Timer();
start();
}
public void start()
{
timer.schedule(new TimerTask()
{
#Override
public void run()
{
System.out.println("hi");
}
}, 500);
}
public void reset()
{
timer.cancel();
timer.purge();
start();
}
}
Create instance
private Timerr timer = new Timerr();
Do your reset
if(condition)
{
timerr.reset();
}
You may want to check out Java's Swing timer. It works somewhat differently and you may have to write an internal class or an actionlistener, but the Swing timer includes .stop() and .restart(), which seem like they would work better in your application.

Scheduling java process for a specific time interval with a given delay

We want to schedule a java process to run till a specific time interval. Currently I am thinking to using TimerTask to schedule this process. In the start of every loop, will check the current time and then compare with the given time and stop the process if the time is elapsed.
Our code is something like below:
import java.util.Timer;
import java.util.TimerTask;
public class Scheduler extends TimerTask{
public void run(){
//compare with a given time, with getCurrentTime , and do a System.exit(0);
System.out.println("Output");
}
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
Timer timer = new Timer();
timer.scheduleAtFixedRate(scheduler, 0, 1000);
}
}
Is there a better approach for this?
Instead of checking if the time limit has been reached in every single iteration you could schedule another task for the said time limit and call cancel on your timer.
Depending on the complexity you might consider using a ScheduledExecutorService such as ScheduledThreadPoolExecutor. See in this answer when and why.
Simple working example with timer:
public class App {
public static void main(String[] args) {
final Timer timer = new Timer();
Timer stopTaskTimer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println("Output");
}
};
TimerTask stopTask = new TimerTask() {
#Override
public void run() {
timer.cancel();
}
};
//schedule your repetitive task
timer.scheduleAtFixedRate(task, 0, 1000);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2015-06-09 14:06:30");
//schedule when to stop it
stopTaskTimer.schedule(stopTask, date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You can use RxJava, a very powerful library for reactive programming.
Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
t.subscribe(new Action1() {
#Override
public void call(Object o) {
System.out.println("Hi "+o);
}
}
) ;
try {
Thread.sleep(10000);
}catch(Exception e){ }
You can even use the lambda syntax:
Observable t = Observable.timer(0, 1000, TimeUnit.MILLISECONDS);
t.forEach(it -> System.out.println("Hi " + it));
try {
Thread.sleep(10000);
}catch(Exception e){ }

Incremental Timer

I'm currently using a Timer and TimerTask to perform some work every 30 seconds.
My problem is that after each time I do this work I want to increment the interval time of the Timer.
So for example it starts off with 30 seconds between the timer firing but I want to add 10 seconds to the interval then so that the next time the Timer takes 40 seconds before it fires.
Here is my previous code:
public void StartScanning() {
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.startScan();
scanCount++;
if(SCAN_INTERVAL_TIME <= SCAN_MAX_INTERVAL){
SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;
t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
}
}
});
}};
Log.d("SCAN_INTERVAL_TIME ** ", "SCAN_INTERVAL_TIME ** = " + SCAN_INTERVAL_TIME);
t.schedule(scanTask, 0, SCAN_INTERVAL_TIME);
}
REFACTORED CODE
#Override
public void StartScanning() {
t.schedule(new ScanTask(),SCAN_INTERVAL_TIME);
}
class ScanTask extends TimerTask{
#Override
public void run() {
wifiManager.startScan();
scanCount++;
if(SCAN_INTERVAL_TIME < SCAN_MAX_INTERVAL)
SCAN_INTERVAL_TIME = SCAN_INTERVAL_TIME + SCAN_INCREASE_INTERVAL;
t.schedule(new ScanTask(), SCAN_INTERVAL_TIME);
}
}
It works now but is creating a new ScanTask() every time wasteful?
Here is how I would do it:
1) Schedule the task for a single execution rather than a repeated one
2) At the end of the execution (possibly in a finally block), schedule a new single execution of the task, with a longer delay. Note that you must create a new instance of the task, otherwise the timer will complain (IllegalStateException). That means that you can't use an anonymous inner class anymore.

Calling a function every 10 minutes

I'm not an expert, just a beginner. So I kindly ask that you write some code for me.
If I have two classes, CLASS A and CLASS B, and inside CLASS B there is a function called funb(). I want to call this function from CLASS A every ten minutes.
You have already given me some ideas, however I didn't quite understand.
Can you post some example code, please?
Have a look at the ScheduledExecutorService:
Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
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);
}
}
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ClassExecutingTask {
long delay = 10 * 1000; // delay in milliseconds
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
private class LoopTask extends TimerTask {
public void run() {
System.out.println("This message will print every 10 seconds.");
}
}
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
}
Try this. It will repeat the run() function every set minutes. To change the set minutes, change the MINUTES variable
int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() { // Function runs every MINUTES minutes.
// Run the code you want here
CLASSB.funcb(); // If the function you wanted was static
}
}, 0, 1000 * 60 * MINUTES);
// 1000 milliseconds in a second * 60 per minute * the MINUTES variable.
Don't forget to do the imports!
import java.util.Timer;
import java.util.TimerTask;
For more info, go here:
http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html
public class datetime {
public String CurrentDate() {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
return currentTime;
}
public static void main(String[] args) {
class SayHello extends TimerTask {
datetime thisObj = new datetime();
public void run() {
String todaysdate = thisObj.CurrentDate();
System.out.println(todaysdate);
}
}
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);
}
}
Solution with Java 8
ClassB b = new ClassB();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
b.funb();
};
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);

Categories