Is there anyway I can exit a java program after a couple of seconds e.g. 5 seconds.
I know you can quit the java program using:
System.exit(0);
But I'm not sure whether the 0 stands for seconds since this code:
System.exit(10);
also exits instantly
System.exit(0) specifies the exit error code of the program.
you can put it on a timer and schedule the task
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimedExit {
Timer timer = new Timer();
TimerTask exitApp = new TimerTask() {
public void run() {
System.exit(0);
}
};
public TimedExit() {
timer.schedule(exitApp, new Date(System.currentTimeMillis()+5*1000));
}
}
and then you can just called TimedExit()
You can invoke Thread.sleep() just before you exit your program:
// Your code goes here.
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
// log the exception.
}
System.exit(0);
From System.exit(int) method documentation:
Terminates the currently running Java Virtual Machine. The argument
serves as a status code; by convention, a nonzero status code
indicates abnormal termination.
If you need to execute something during the time waiting for exit, you could create a control thread, that will just wait for the right time to perform the exit like this:
public class ExitFewMiliseconds {
public static void main(String args[]) {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}).start();
while (true) {
System.out.println("I'm doing something");
}
}
}
If nothing shall be executing while waiting for exit, you could simply use a Thread.sleep(ms)
The 0 you pass into System.exit(0) has nothing to do with how long it will wait before exiting. Javadocs are your friend. From the javadoc:
The argument serves as a status code; by convention, a nonzero status
code indicates abnormal termination.
Other answers already cover how to wait 5 seconds before exiting if you really need to do that.
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task
* to execute once 5 seconds have passed.
*/
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.format("Time's up!%n");
System.exit();
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(10);
System.out.format("Task scheduled.%n");
}
}
In this way you can use the Timer class and exit the system after a particular time interval
Related
I have a thread which is in charge of doing some processes. I want make it so that these processing would be done every 3 seconds. I've used the code below but when the thread starts, nothing happens.
I assumed that when I define a task for my timer it automatically execute the ScheduledTask within time interval but it doesn't do anything at all.
What am I missing?
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
increaserTimer.schedule(increaseTemperature, 3000);
}
};
A few errors in your code snippet:
You extend the Thread class, which is not really good practice
You have a Timer within a Thread? That doesnt make sense as the a Timer runs on its own Thread.
You should rather (when/where necessary), implement a Runnable see here for a short example, however I cannot see the need for both a Thread and Timer in the snippet you gave.
Please see the below example of a working Timer which will simply increment the counter by one each time it is called (every 3seconds):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
System.out.println("TimerTask executing counter is: " + counter);
counter++;//increments the counter
}
};
Timer timer = new Timer("MyTimer");//create a new Timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//this line starts the timer at the same time its executed
}
}
Addendum:
I did a short example of incorporating a Thread into the mix. So now the TimerTask will merely increment counter by 1 every 3 seconds, and the Thread will display counters value sleeping for 1 seconds every time it checks counter (it will terminate itself and the timer after counter==3):
import java.util.Timer;
import java.util.TimerTask;
public class Test {
static int counter = 0;
static Timer timer;
public static void main(String[] args) {
//create timer task to increment counter
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
};
//create thread to print counter value
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
System.out.println("Thread reading counter is: " + counter);
if (counter == 3) {
System.out.println("Counter has reached 3 now will terminate");
timer.cancel();//end the timer
break;//end this loop
}
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
timer = new Timer("MyTimer");//create a new timer
timer.scheduleAtFixedRate(timerTask, 30, 3000);//start timer in 30ms to increment counter
t.start();//start thread to display counter
}
}
import java.util.Timer;
import java.util.TimerTask;
public class ThreadTimer extends TimerTask{
static int counter = 0;
public static void main(String [] args) {
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(new ThreadTimer(), 30, 3000);
}
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("TimerTask executing counter is: " + counter);
counter++;
}
}
In order to do something every three seconds you should use scheduleAtFixedRate (see javadoc).
However your code really does nothing because you create a thread in which you start a timer just before the thread's run stops (there is nothing more to do). When the timer (which is a single shoot one) triggers, there is no thread to interrupt (run finished before).
class temperatureUp extends Thread
{
#Override
public void run()
{
TimerTask increaseTemperature = new TimerTask(){
public void run() {
try {
//do the processing
} catch (InterruptedException ex) {}
}
};
Timer increaserTimer = new Timer("MyTimer");
//start a 3 seconds timer 10ms later
increaserTimer.scheduleAtFixedRate(increaseTemperature, 3000, 10);
while(true) {
//give it some time to see timer triggering
doSomethingMeaningful();
}
}
I think the method you've used has the signature schedule(TimerTask task, long delay) . So in effect you're just delaying the start time of the ONLY execution.
To schedule it to run every 3 seconds you need to go with this method schedule(TimerTask task, long delay, long period) where the third param is used to give the period interval.
You can refer the Timer class definition here to be of further help
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
Timer & TimerTask are legacy
The Timer & TimerTask classes are now legacy. To run code at a certain time, or to run code repeatedly, use a scheduled executor service.
To quote the Timer class Javadoc:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
Executor framework
In modern Java, we use the Executors framework rather than directly addressing the Thread class.
Define your task as a Runnable or Callable. You can use compact lambda syntax seen below. Or you can use conventional syntax to define a class implementing the Runnable (or Callable) interface.
Ask a ScheduledExecutorService object to execute your Runnable object’s code every so often.
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor() ;
Runnable task = () -> {
System.out.println( "Doing my thing at: " + Instant.now() );
};
long initialDelay = 0L ;
long period = 3L ;
TimeUnit timeUnit = TimeUnit.SECONDS ;
scheduledExecutorService.submit( task , initialDelay, period , timeUnit ) ;
…
scheduledExecutorService.shutdown() ; // Stops any more tasks from being scheduled.
scheduledExecutorService.awaitTermination() ; // Waits until all currently running tasks are done/failed/canceled.
Notice that we are not directly managing any Thread objects in the code above. Managing threads is the job of the executor service.
Tips:
Always shutdown your executor service gracefully when no longer needed, or when your app exits. Otherwise the backing thread pool may continue indefinitely like a zombie 🧟♂️.
Consider wrapping your task's working code in a try-catch. Any uncaught exception or error reaching the scheduled executor service results in silently halting the further scheduling of any more runs.
The version of Java is 8u60.
I want to write a void method which could pause the program for 1 seconds but there are always exceptions.
public void OnePause(){
Timer timerOne = new Timer();
timerOne.schedule(timerOneTask(), (long)1000);}
private TimerTask timerOneTask() {
return null;
}
}
I do not want to use Thread.Sleep(); because it pauses the sum of all time when called multiple times instead of pause separately.
Thanks a lot.
Right now your code is broken. Besides trying to send null into Timer.schedule(...), your statement timerOne.schedule(timerOneTask(), (long)1000);} is going to call timerOneTask() every 1000 milliseconds, but that does not pause the program. You must sleep the thread:
private TimerTask timerOneTask(int sleepTime) {
return new DoNothingTimerTask extends TimerTask {
public void run() {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// awoken prematurely, handle this
}
}
}
Unless you need to schedule the "pauses" on some interval, there's no use in introducing the Timer API into the mix; if not, you can get simply use what's in that try...finally block.
I have an old application that has a robot thread that executes everyday. I have the source for the robot, but I don't know how this tread is started. And there's a log, witch includes a line in a database, that sometimes includes 2 identical lines, proving that the process is executing doubled.
we use Windows Server 2003
public void run()
{
while (true)
{
starter();
try {
Thread.sleep(10800000L);
}
catch (InterruptedException localInterruptedException)
{
}
}
}
I need to keep it from executing more than once.
I'm new to treads, don't really get the works of a thread right yet...
thank you all in advance...
You don't really provide a lot of information, but here are a few guesses:
Could the entire process be launched twice?
If the thread is running twice, showing the thread run function won't help. You'll have to find the code that creates the thread.
Log something in the catch block. Maybe a sleep call gets interrupted immediately and this is why starter() is called twice at almost the same time.
public void run()
{
int delay = 86400000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
starter();
}
};
new Timer(delay, taskPerformer).start();
}
Or...
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class DailyTask extends TimerTask {
#Override
public void run() {
//Or if you use a logger like log4j you can insert logger code here.
System.out.println("Start:" + new Date());
starter();
System.out.println("End:" + new Date());
}
public static void main(String args[]) {
TimerTask tt= new DailyTask();
// running timer task as daemon thread
Timer t = new Timer(true);
t.scheduleAtFixedRate(tt, 0, 86400000);
System.out.println("DailyTask started:" + new Date());
}
}
This should run starter() once every 24 hours.
I have a JRuby engine which evaluates some scripts and I want to close the thread if it takes more than 5 seconds.
I tried something like this:
class myThread extends Thread{
boolean allDone = false;
public void threadDone() {
allDone = true;
}
public void run() {
while(true) {
engine.eval(myScript);
if(allDone)
return;
}
}
(...)
th1 = new myThread();
th1.start();
try {
Thread.sleep(5000);
if(th1.isAlive())
th1.threadDone();
} catch(InterruptedException e) {}
if(th1.isAlive())
System.out.println("Still alive");
I also tried to kill the thread with th1.stop() or th1.interrupt() but the value retured by th1.isAlive() method is always true.
What can I do?
I want to add that myScript could be "while(1) do; end" and I cannot wait until it's completed. So I want to prevent scripts like that and kill the thread if it takes more than 5 seconds.
Another solution would be to use the built-in mechanism to interrupt threads:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
engine.eval(myScript);
}
}
...
th1 = new myThread();
th1.start();
try {
Thread.sleep(5000);
th1.interrupt();
}
This way, no need for an allDone field, and no risk in failing to synchronize.
To make your Thread stoppable you might want something like.
class MyTask implements Runnable {
public void run() {
try {
engine.eval(myScript);
} catch(ThreadDeath e) {
engine = null; // sudden death.
}
}
}
You can call Thread.stop(), but I suggest you read the warnings on this method first.
If you want a thread to run for up to 5 seconds, the simplest solution is for the thread to stop itself.
class MyTask implements Runnable {
public void run() {
long start = System.currentTimeMillis();
do {
engine.eval(myScript);
} while(System.currentTimeMillis() < start + 5000);
}
}
This assumes you want to run engine.eval() repeatedly. If this is not the case you may have to stop() the thread. It is deprecated for a good reason but it might be your only option.
I'm about to learn the java threading facility.
I have 2 classes:
public class Main {
public static void main(String[] arg) throws Exception {
Timer timer = new Timer();
timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);
try {
Thread.currentThread().join();
} catch (InterruptedException ex) {
System.out.println("timer stopped");
}
System.out.println("try block executed");
}
}
and the timer class:
public class ExecuteTimer extends TimerTask {
public ExecuteTimer(Thread thread) {
creatingThread = thread;
}
private Thread creatingThread;
#Override
public void run() {
System.out.println("I'm executed!");
creatingThread.interrupt();
}
}
When I debug the code. I have following output:
I'm executed!
timer stopped
try block executed
Everything seems to be final except the app didn't exit after I have the output above. The eclipse remain in debug mode and no exception has been thrown.
After you no longer need the Timer to run tasks, you should call timer.cancel() to release its thread.
Use thread.setDaemon(true) to tell the JVM to make the thread a daemon thread. Daemon threads do not prevent the program from exiting.