Tryllion
Tryllion

Reputation:

How to run a method at XX:XX:XX time?

HI

I want to run a method in my program evry X hours, how to do that ? Im googling and there is nothing :/

Upvotes: 1

Views: 368

Answers (5)

Hugi
Hugi

Reputation: 212

I use the Quartz framework for most of my scheduling ( http://www.quartz-scheduler.org/ ) but if you're doing something simple, java.util.Timer is fine.

// in a class body...

public static void main( String[] argv ) {
    Timer timer = new Timer();
    int secondsBetweenRuns = 3600;
    timer.schedule( new MyOwnTask(), 0, secondsBetweenRuns * 1000 );
}

static class MyOwnTask extends TimerTask {

    public void run() {
        doWhateverYouNeedToDoEveryHour();
    }
}

Upvotes: 2

Jonathan Holloway
Jonathan Holloway

Reputation: 63672

You could take a look at the Timer class, but the best option is to use a ScheduledExecutorService:

e.g. This will beep at a scheduled rate:

import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {

        final Runnable beeper = new Runnable() {
                public void run() { 
                    System.out.println("beep"); 
                }
            };

        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);

        scheduler.schedule(new Runnable() {
                public void run() { 
                    beeperHandle.cancel(true); 
                }
        }, 60 * 60, SECONDS);
    }
 }

Upvotes: 6

idrosid
idrosid

Reputation: 8029

You could consider Quartz.

It is some sort of cron that runs inside java. I admit though that it is probably an overkill if you want to schedule only one job.

Upvotes: 9

Steve
Steve

Reputation: 12393

You could save the time at a certain point, than start a timer. When the time is up, you run the method and restart the timer.

Upvotes: 0

Adrian Godong
Adrian Godong

Reputation: 8921

Scheduled Task (in Windows) or Cron (in Unix)

Upvotes: 0

Related Questions