I'm trying to write script in groovy that does a some http requests and measure the time of it. Unfortunately, there are some requests that may be too slow to wait for it. I need to check if they are running for some part of time (eg. 1 minute) and if they didn't stop, I need to force stop of executing it.
start = new Date()
value = select.toURL().text // this needs to be timeouted after 1 minute
stop = new Date()
Take a look at
import java.util.Timer;
https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
Then you can schedule a task like:
// creating timer task, timer
TimerTask tasknew = new TimerSchedulePeriod();
Timer timer = new Timer();
// scheduling the task at interval
timer.schedule(tasknew,100, 100);
Or if you are lazy something like:
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your code here
}
}, timeInMilli);
Related
I want to make my millisecond time change every 100ms, but the time I get is inconsistent sometimes the intervals I get are 99, 100 and 101. The interval I want is 100 and consistent.
as below my problem is now the resulting interval will change like number 4 and 5.
19:56:16:096
19:56:16.196
19:56:16.296
19:56:16.397
19:56:16.495
while the result I want is like this below
19:56:16.096
19:56:16.196
19:56:16.296
19:56:16.396
19:56:16.496
here's a screenshot of my App
here's the code I use
public void startTimer(){
carousalTimer = new Timer(); // At this line a new Thread will be created
carousalTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//DO YOUR THINGS
runOnUiThread(new Runnable() {
#Override
public void run() {
long time = System.currentTimeMillis();
SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = new Date();
data = sdf3.format(time).toString();
aList.add(data);
get(data);
}
});
}
}, 100, 100); // delay
}
I believe it is part of how Android works. It is a multi-threaded environment where resources are share among multiple processes.
According to the documentation Timer.scheduleAtFixedRate() is the best approach for the following use cases:
In fixed-rate execution, each execution is scheduled relative to the
scheduled execution time of the initial execution. If an execution is
delayed for any reason (such as garbage collection or other background
activity), two or more executions will occur in rapid succession to
"catch up." In the long run, the frequency of execution will be
exactly the reciprocal of the specified period (assuming the system
clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are
sensitive to absolute time, such as ringing a chime every hour on the
hour, or running scheduled maintenance every day at a particular time.
It is also appropriate for recurring activities where the total time
to perform a fixed number of executions is important, such as a
countdown timer that ticks once every second for ten seconds. Finally,
fixed-rate execution is appropriate for scheduling multiple repeating
timer tasks that must remain synchronized with respect to one another.
https://developer.android.com/reference/java/util/Timer#scheduleAtFixedRate
If it is only necessary to be visual perfect, you can set the time relative to the start time. For example by increment an index every 100ms:
final long DELAY = 100; // 100ms delay
AtomicInteger index = AtomicInteger(0);
long startTime = System.currentTimeMillis();
carousalTimer = new Timer(); // At this line a new Thread will be created
carousalTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
long time = startTime + (index.incrementAndGet() * DELAY)
SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = new Date();
data = sdf3.format(time).toString();
aList.add(data);
get(data);
}
});
}
}, DELAY, DELAY);
I'm trying to start, end, and reset+restart a timer using two different if statements in the onDataChange method. The thing I can't get to work is getting the timer to restart if the first if statement is triggered again after the second one stops the timer. After the class declaration at the top, I have
Timer firstTestTimer = new Timer();
TimerTask increaseByTwo = new TimerTask() {
#Override
public void run() {
incrementalCount = incrementalCount + 2;
System.out.println(incrementalCount);
}
};
and in the onCreate method I have a Firebase reference with a ValueEventListener with the following code:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String Motion1 = dataSnapshot.child("Enter").getValue().toString();
if(Motion1.equals("YES")){
incrementalCount = 0;
firstTestTimer.schedule(increaseByTwo, 2000,2000);
}
if(Motion1.equals("STOP")){
firstTestTimer.cancel();
firstTestTimer.purge();
System.out.println("Total seconds elapsed since sensor showed YES: "+incrementalCount);
if(incrementalCount > 11){
System.out.println("The difference is greater than 11 seconds");
}
}
}
As of right now, when the Firebase value initially changes to "YES", the timer starts and every two seconds it increases incrementalCount by 2. When the Firebase value changes to "STOP", the timer shows the correct amount of seconds that have passed. Here's the problem: When the Firebase value changes to "YES" again, the app crashes and gives me some variation of java.lang.IllegalStateException: Task already scheduled or cancelled
Is it possible to reset and restart the timer with a fresh count whenever the Firebase value changes to "YES"? Thank you!
As #ThomasKläger pointed out, you can't use a TimerTask again. The docs point out that:
A timer task is not reusable. Once a task has been scheduled for execution on a Timer or canceled, subsequent attempts to schedule it for execution will throw IllegalStateException.
It is like a plastic cup or spoon, built to be used only once. So every time you have to increment your timer, here's what you can do:
Leave the timer as it is and define the timer task object again:
if (Motion1.equals("YES")){
incrementalCount = 0;
//Define it again, I think it is a waste of time to check whether the task exists or not.
increaseByTwo = new TimerTask() {
#Override
public void run() {
incrementalCount = incrementalCount + 2;
System.out.println(incrementalCount);
}
};
firstTestTimer.schedule(increaseByTwo, 2000,2000);
}
The rest of the code is the same. This should work.
The documentation for TimerTask is here: TimerTask JDK 11
I have a timer which runs on the activity's OnCreate method as shown below. When run, the timer increments as it should. Showing:
00:00,
00:01,
00:02,
etc.
final Timer timer = new Timer();
final TimerTask timerTask = new TimerTask(){
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String timer = sdf.format(new Date(counter * 1000L));
timerText.setText(timer);
counter++;
}
});
}};
timer.schedule(timerTask, 0, 1000);
However, when I revisit the activity, the timer's interval increases. If I revisit it the first time, the interval becomes 2 i.e.
00:00,
00:02,
00:04,
etc.
Revisiting it again makes the interval 3 i.e.
00:00,
00:03,
00:06,
etc.
And the intervals keep incrementing.
I deduced the runOnUIThread method is being run n times, where n is the number of times onCreate has been accessed, but I don't really know what to do about it.
Use the Timer constructor that specifies it to be a daemon new Timer(true) so that if it exits the timer thread exits too.
Also consider cancelling the timer before exiting on onDestroy or onPause for example.
I am using timer.schedule(minuteTask, 0, 1000*60) to generate a new color at regular intervals. As you can see by the gif below that I recorded, the interval does not seem to be working.
Timer timer = new Timer ();
TimerTask minuteTask = new TimerTask() {
#Override
public void run () {
java.util.Random random = new java.util.Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
}
};
timer.schedule(minuteTask, 0, 1000*60);
Any idea on how to fix this?
Use this
new Timer().scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
//put UR code herr
}
}, 0, 1000);
Hi I think you should use the scheduleAtFixedRate(..) function of Timer. This will help you to change the color in given time interval.
A simple schedule() method will execute at once while scheduleAtFixedRate() method takes and extra parameter which is for repetition of the task again & again on specific time interval.
Look at below code snippet:
Timer timer = new Timer();
timer.schedule( new performClass(), 30000 );
This is going to perform once after the 30 Second Time Period Interval is over. A kind of timeoput-action.
Timer timer = new Timer();
//timer.scheduleAtFixedRate(task, delay, period);
timer.scheduleAtFixedRate( new performClass(), 1000, 30000 );
This is going to start after 1 second and will repeat on every 30 seconds time interval.
I have an if statement which evaluates the time since the program has begun running and if the time is above a certain threshold, does something. I want this if statement to be checked throughout the whole time the program is running while at the same time have the program continue execution. How would I go about doing this?
Thank you.
The easiest approach would be to use a Timer. With that, you don't need the if logic; you can just use the firstTime argument when scheduling a TimerTask.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// do something
}
};
// schedule the task to be run every 100ms (0.1 sec),
// starting after "threshold" milliseconds have past
timer.schedule(task, threshold, 100);
It's not clear from your description if you want to repeatedly "do something" once the time threshold has been exceeded, or if you just want to wait until a certain time has passed and then "do something" once. The above code is for the repeating case. For a one-shot occurrence at some future time, change the last line to:
timer.schedule(task, threshold);
If you're using Swing, you should use a Swing Timer rather than a java.util.Timer. See How to Use Swing Timers for more info.
EDIT: Your comment clarified things a bit. It's fairly easy to do what you described:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
private final long start = System.currentTimeMillis();
#Override
public void run() {
if (System.currentTimeMillis() - start < threshold) {
// do something
} else {
// do something else
}
}
};
// schedule the task to be run every 100ms (0.1 sec), starting immediately
timer.schedule(task, 0, 100);
Note that "do something" and "do something else" can be method calls to an enclosing class.
A cleaner approach might be to define several TimerTasks that are scheduled to execute at different times. The "something else" task that triggers an exception can be scheduled for one-time execution at the threshold time. You can also cancel individual tasks and you can even schedule a task that will cancel another task.