0

How can i implement code to do something when a specific system time is reached? The only solution i have thought of is using a timer to "tick" every few minutes or hours to check if the specific time has been reached.

Are there any other better solutions ?

Thanks.

sorry if i had not been clear, i would be implementing the code inside my Java program, it is to clear records of a log before a new day is coming and save the records.

Example: Clear the current records and save these records at 23:59.

sutoL
  • 1,697
  • 10
  • 27
  • 45
  • 2
    Create a simple script that could run your Jar file at any given time. – Tdorno May 15 '13 at 02:20
  • Related: http://stackoverflow.com/questions/2488736/run-a-program-or-method-at-specific-time-in-java – Rob Hruska May 15 '13 at 02:23
  • 1
    If you're trying to manage logs you could use [logback](http://logback.qos.ch/) or [log4j](http://logging.apache.org/log4j/1.2/) instead. – Rob Hruska May 15 '13 at 02:26

7 Answers7

2

In pure Java, there is a Timer class. This is useful if you have a program running already. Or you are running a web app that is always up.

Another alternative is to use operating system (UNIX cron) and have it start the Java program at that time. This is useful if you don't meet the conditions for Timer.

Jeanne Boyarsky
  • 11,880
  • 2
  • 44
  • 58
1

You can just make a timer with a long duration. If the trigger time will be 350 minutes from now, there's no point having a timer poll every minute to see if the time is reached. Just set your timer to 350 minutes. Once it fires, remove the timer. This is called a one-shot timer. I can't answer how to specifically do this in Java, unfortunately.

paddy
  • 52,396
  • 6
  • 51
  • 93
1

If you are using Unix-like systems have a look at cron

If you are on Windows have a look at What is the Windows version of cron?

Community
  • 1
  • 1
Craig
  • 1,402
  • 7
  • 12
1

Quartz Scheduler Framework is an enterprise class framework that can be used as a Timer.

Rudy
  • 6,358
  • 9
  • 42
  • 79
1

if i understand your question correctly, for unix, you can put your code in crontab and schedule it to run at specific system time. while for windows, you can use task scheduler. this is how we do it to run specific test scripts for nightly builds.

kenny.g
  • 19
  • 5
0

did you try Quartz Scheduler? , it is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time.click here for more

Potato
  • 3,320
  • 2
  • 14
  • 31
0

I think java.util.concurrent.ScheduledExecutorService is enough.