Schedule a java task to run at a certain time, and wrap it as a windows service

To make a Java program that runs at certain time is not difficult, we can just use java.util.Timer and java.util.TimerTask classes, here is the code.

public class Main {
	public static void main(String[] args) {
		Timer timer = new Timer();
		TimerTask tt = new TimerTask(){
			public void run(){
				Calendar cal = Calendar.getInstance(); //this is the method you should use, not the Date(), because it is desperated.
				int hour = cal.get(Calendar.HOUR_OF_DAY);//get the hour number of the day, from 0 to 23
				if(hour == 14){
					System.out.println("doing the scheduled task");
		timer.schedule(tt, 1000, 1000*5);//	delay the task 1 second, and then run task every five seconds

Then we need wrap this application as a windows service which can run automatically after system is turned on.
I use Java Service Wrapper, here is a very good tutorial to show how to use it using Method 3. If there is any problem, let me know and maybe I can help.

Category >> Real Methods  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Planitel on 2013-9-25

    Nice thanks, really helpfull, I finally solved my problem.

  2. sailesh on 2014-12-6

    Thanks a lot for this useful example!

  3. indrajit narvekar on 2015-10-20

    Thanks it works well

Leave a comment