I need help understanding the scheduleAtFixedRate method of theTimer class in java - java

Being a fan of the Pomodoro technique I'm making myself a countdown timer to keep me on task with my homework. This particular project, however, is NOT homework. :)
Stack has a LOT of questions about using timers to control delays before user input and the like, but not a lot on standalone timers. I've run across this code from a friend, and have studied the class on Java Documentation.
public class Stopwatch {
static int interval;
static Timer timer;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input seconds => : ");
String secs = sc.nextLine();
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = Integer.parseInt( secs );
System.out.println(secs);
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval()
{
if( interval== 1) timer.cancel();
return --interval;
}
}
There is some syntax that's not clear to me. Consider:
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
I'm not understanding how the parentheses and braces work. At first glance, given the usage of scheduleAtFixedRate(TimerTask task, long delay, long period) I can see the delay and period parameters, but not an open paren preceding first parameter.
Is my first parameter actually this whole block of code? I would expect the whole block to be surrounded by parentheses...but it's not. Is this a common syntax in java? I've never run across it before.
new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}
I just want to clarify that I understand it before I start mucking about with changes.

timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}, delay, period);
That code is equivalent to this refactoring, where the new TimerTask is assigned to a local variable.
TimerTask task = new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
};
timer.scheduleAtFixedRate(task, delay, period);
Of course the weird part has just moved upwards a bit. What is this new TimerTask stuff, exactly?
Java has special syntax for defining anonymous inner classes. Anonymous classes are a syntactical convenience. Instead of defining a sub-class of TimerTask elsewhere you can define it and its run() method right at the point of usage.
The code above is equivalent to the following, with the anonymous TimerTask sub-class turned into an explicit named sub-class.
class MyTimerTask extends TimerTask
{
public void run()
{
System.out.println(setInterval());
}
}
TimerTask task = new MyTimerTask();
timer.scheduleAtFixedRate(task, delay, period);

You are correct, the first parameter is the entire code block:
new TimerTask()
{
public void run()
{
System.out.println(setInterval());
}
}
These declarations are called Anonymous classes and are explained in more detail in the Java Tutorials.

It is a anonymous inner class. You need to study inner classes for understanding this. Generally such classes are used when you do not need the class to be used else where in your code. You cannot use it else where just because you dont have reference pointing to it.
You can also replace the above code as follows :
class MyTimerTask extends TimerTask {
#Override
public void run() {
// Timer task code goes here.
System.out.println(setInterval());
}
}
MyTimerTask timerTask = new MyTimerTask();
timer.scheduleAtFixedRate(timerTask, delay, period);

Related

How to schedule a method with TimerTask but with different method parameter the first time

This is the first time I post something in the beautiful and awesome StackOverflow community and my english is a bit rusty, but I'll try to explain the best I can.
I have the following situation:
In my main, I'm invoking a method through a TimerTask, because I need to schedule it so the method is executed every 5 seconds. Here is my main:
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
methodWithParams("HelloWorld");
}
};
timer.scheduleAtFixedRate(timerTask, 0, 5000);
}
And here is the invoked method:
public static void methodWithParams(String param){
System.out.println("Incoming Param: "+param);
}
With this, the output is like this every 5 seconds:
Incoming Param: HelloWorld
What I want is to run methodWithParams method every 5 seconds, but the first time that method is invoked, I can call it with some param but the rest of the time the param is anything else, so the result is something like this:
Incoming Param: HelloWorld
Incoming Param: HelloWorld2
Incoming Param: HelloWorld2
Incoming Param: HelloWorld2
How can I do that? Any suggests?
Thank you very much in advance!!
I found a solution to my problem and I deleted the post (my fault). I undeleted so the solution can be available for someone who has the same question I had.
What I did was this: By creating a boolean class var inside the task, I was able to control if it was the first execution or not since the task behaves like a loop.
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
boolean first = true;
#Override
public void run() {
if(first){
first = false;
methodWithParams("HelloWorld");
}else{
methodWithParams("HelloWorld2");
}
}
};
timer.scheduleAtFixedRate(timerTask, 0, 5000);
}

Java timer that limits the amount of time a method can run for

I am writing a web crawler and part of the specifications is that it will crawl the web for a user-specified amount of time. In order to do that I am trying to use the Timer and TimerTask methods. The code I have now is attempt number two. I have watched a few tutorials though none of them are quite what I need. I have also read through the documentation. I have been working on this project for a few weeks now and it is due tonight. I am not sure where to turn to next.
public void myTimer (String url, long time)
{
Timer webTimer = new Timer();
TimerTask timer;
timer = new TimerTask()
{
public void run()
{
long limit = calculateTimer(time);
while(System.currentTimeMillis() < limit)
{
webcrawler crawler1 = new webcrawler();
crawler1.Crawl(url);
}
System.out.println("times Up");
}
};
webTimer.schedule(timer, 1000);
}
I am guessing the .Crawl() is starting a loop and keeping that thread busy, which means it cannot check the while condition. I do not know your implementation of the crawler but i would recommend a function stopCrawling which would set a boolean to true to break the loop inside that class. Than I would do something like this:
public void startCrawler (String url, long time){
webcrawler crawler1 = new webcrawler();
crawler1.Crawl(url);
TimerTask task = new TimerTask() {
public void run() {
crawler1.stopCrawling()
}
};
Timer timer = new Timer("Timer");
timer.schedule(task, time);
}

Java: run a method periodcally using timer

I've a Java project which is main create an instance of a class (ThreadClient) that extends Thread. I would need that ThreadClient.run starts 2 timers to run periodically 2 methods of the ThreadClient class.
The examples I found in internet just show that the timer can start the run method of an instance of a classe that exteds the Thread class.
I woundln't need to create a new class, just to run 2 methods of the same class that creates the timers.
Something like C# does:
public class ThreadClient
{
private Timer _timer;
public ThreadClient() {
Start();
}
private void Start()
{
_timer = new Timer(3000); // Set up the timer for 3 seconds
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true; // Enable it
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
// do something
}
}
Method _timer_Elapsed belongs to the class that creates the timer.
Thanks in advance,
Samuel
That's how I finally reached my goal:
// Timer to process sales
TimerTask ttProcessSales = new TimerTask() {
#Override
public void run() {
processSales();
}
};
Timer tProcessSales = new Timer();
tProcessSales.schedule(ttProcessSales, 0, this._processTaskTimeInterval);
// Timer to process tasks
TimerTask ttProcessTask = new TimerTask() {
#Override
public void run() {
processTasks();
}
};
Timer tProcessTasks = new Timer();
tProcessTasks.schedule(ttProcessTask, 0, this._processTaskTimeInterval);
In this way I can run 2 methods of the class using timers without create new class for every method I needed to execute.

Java util Timer not working correctly

I was wondering if someone might be able to see what I had done wrong here. I am trying to create a timer which will increment the count variable by 1 every second and print it out on the console. However, it prints the first number and then stops and I am not sure what is going on.
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
private Timer timer;
public int count = 0;
public TimerTest() {
timer = new Timer();
timer.schedule(new TimerListener(), 1000);
}
private class TimerListener extends TimerTask {
#Override
public void run() {
count++;
System.out.println(count);
}
}
public static void main(String[] args) {
new TimerTest();
}
}
I did find some other questions like this but none of their solutions made any difference to the result.
Thanks.
Your scheduling only runs the task once. You need to add a parameter to use the method schedule(TimerTask task,
long delay,
long period):
timer.schedule(new TimerListener(), 1000, 1000);

TimerTask keeps running

I have a question about the behaviour of Timer class in Java.
This is the code: http://pastebin.com/mqcL9b1n
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.foo();
m = null;
}
public void foo() {
Timer t = new Timer();
t.schedule(new SysPrint(), 200);
}
}
class SysPrint extends TimerTask {
public void run() {
System.out.println("Yes!");
}
}
What happens is that if you run that program, it will print "Yes!" and it's not gonna do anything else (the program doesn't end).
The Java documentation says:
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection).
As I see this thing, the "last live reference" to the Timer object is gone after the 'foo()' functions ends. And the only task scheduled was the "Yes!" task that was executed, so I guess that after the process printed "Yes!", the Timer object should end and the process should terminate.
What happened here?
Java is not exiting because your thread running the Timer is still kicking around. You have to mark that thread as being a daemon thread before Java will exit. You probably don't have access to the thread itself so unless Timer has a method to mark it so you'll have a hard time doing that. You'll need to manually stop it in a finally clause.
try {
timer = new Timer();
timer.schedule( new SysPrint(), 200 );
} finally {
timer.cancel();
}
I believe the code below should do the trick.
public class Main {
public static void main(String[] args) {
Main m = new Main();
m.foo();
m = null;
}
public void foo() {
Timer t = new Timer();
t.schedule(new SysPrint(), 200);
}
}
class SysPrint extends TimerTask {
SysPrint(Timer timer) {
this.timer = timer;
}
public void run() {
System.out.println("Yes!");
timer.cancel();
}
private Timer timer;
}
When you create a Timer object. A TimerThread is created. And it the internal thread to run your task. You can view the method run() of TimerThread. You can see it has a while loop.
private void mainLoop() {
while (true) {....
The TimerThread not set to a daemon, so the main method execute completely, the jvm not exists.
That why your program is always running and don't stop.

Categories