How to kill/stop task/timer with manual given time - java

My code
setSelectedTime(duration){
duration = 5 //this duration can be dynamic. User can select the time in minutes
timer = new Timer();
TimerTask task = new TimerTask() {
public void run(){
try {
performing task Here....
} catch(Exception e) {
log.error("Exception"+e);
}
}
};
timer.schedule(task, duration*60*1000);
}
How to kill the existing timer/task when user change the input.

Related

Closing a SWT application after certain time of inactivity

I'm trying to close a SWT application after certain period of inactive time. I'm finding difficulty in calculating the inactivity period.All that I've tried just shuts the application after the specified amount of time, irrespective of whether I'm still working on the Application.
Below is the code of what I've tried
Timer timer = new Timer();
display.asyncExec(new Runnable(){
public void run() {
while(!shell.isDisposed()){
if (!display.readAndDispatch()){ //if the system is idle
timer.schedule(new TimerTask() { //schedule timer which will trigger after 1min.
#Override
public void run() {
logout();
}
}, 60000);
}
else{ // reschedule the timer
timer.cancel();
Timer timer = new Timer();
}
}
}
});
with this I'm just able to logout after 1 min even if the user is performing something. Is there a way we can check the inactivity time in SWT ?
You can use Display.addFilter to listen for various events that make the app 'active'. Use Display.timerExec to run code in the UI thread repeatedly to check the time since the last event.
Maybe something like:
private Instant lastActive;
....
lastActive = Instant.now();
final Listener listener = new Listener()
{
#Override
public void handleEvent(final Event event)
{
lastActive = Instant.now();
}
};
display.addFilter(SWT.MouseMove, listener);
display.addFilter(SWT.KeyDown, listener);
// TODO more filters if required
final Runnable timer = new Runnable()
{
#Override
public void run()
{
final Instant now = Instant.now();
if (ChronoUnit.SECONDS.between(lastActive, now) > xxx) { // Number of inactive seconds here
System.out.println("inactive"); // Inactive code here
}
else {
display.timerExec(1000, this);
}
}
};
display.timerExec(1000, timer);
... create/open shell ...
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}

Stop Task after Timer is out

How can I stop my Task when the Timer is out or if the algorithm is finished? The Object (Student) has a long variable "dyingTime". After Time is over it should print it out. Or if the algorithm is over it should print out something else.
Here is my code:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if (run) {
doAlgorithm();
sysout(" Beendet ", timeStart);
} else {
timer.cancel();
timer.purge();
sysout(" Tot ", timeStart);
}
}
}; timer.schedule(timerTask, 0, dyingTime);
Where do i put run = false?
Right now the algorithm goes only 5 millisecs, although the dyingTime is set to 1000.

Java - stop Timer during user input (Countdown)

I have implemented a new class, and what I am trying to do is a countdown. This countdown should start before asking for user input. If it ends during the "waiting for user input", then the Timer should "return" a status or something similar to signal that the time is up. Therefore, I will not ask for the input again, but I skip a big part of my program.
Here is what I have:
public class Reminder
{
Timer timer;
public Reminder(int seconds)
{
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask
{
public void run()
{
System.out.println("Time's up!");
timer.cancel();
// here instead of System.exit(0), I should do something like "return status"
System.exit(0);
}
}
}
And where I call it:
Reminder rm = new Reminder(seconds);
do
{
x = Handler.getCoordinates(in, 'x');
y = Handler.getCoordinates(in, 'y');
// ... other stuff here
} while(!result);

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){ }

How to start a Timer which executes regularly but for a fixed period of time

I am developing a system which has to start a task (download a file) regularly every N seconds. This is not a problem I did it using Timerand Timertaskas follows:
FileTimer rXMLFileTimer;
private static Timer timer = new Timer("FileReader");
rXMLFileTimer = new ReadFileTimer();
int myDelay = 30;
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000);
and the timertask will run until rXMLFileTimer.cancel() is called. Up to now no problem.
Now, It has been required that this timertask should run until the rXMLFileTimer.cancel() is called or a given amount of time.
My first approach (which didn't work) was to implement a Futureas follows:
public class Test {
public static class MyJob implements Callable<ReadFileTimer> {
#Override
public ReadFileTimer call() throws Exception {
Timer timer = new Timer("test");
ReadFileTimer t = new ReadFileTimer();
int delay = 10;
// Delay in seconds
timer.schedule(t, 0, delay * 1000);
return t;
}
}
public static void main(String[] args) {
MyJob job = new MyJob();
System.out.println(new Date());
Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job);
ReadFileTimer timerTask = null;
try {
int maxAmountOfTime = 30;
timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
control.cancel(true);
} catch (InterruptedException ex) {
} catch (ExecutionException ex) {}
}
}
This is not working because I cannot call timerTask.cancel() after the timeout has happen. Then my question is: How can I start a timerTaskfor a given amount of time?
Thanks!
Why not just throw in a second timer task to cancel the first? For example, this code prints the date every second for ten seconds:
public static void main(String[] args) throws Exception {
Timer timer = new Timer();
final TimerTask runUntilCancelledTask = new TimerTask() {
#Override
public void run() {
System.out.println(new Date());
}
};
timer.schedule(runUntilCancelledTask, 0, 1000);
timer.schedule(new TimerTask() {
#Override
public void run() {
runUntilCancelledTask.cancel();
}
}, 10000); // Run once after delay to cancel the first task
}

Categories