Nisal Thiwanka
Nisal Thiwanka

Reputation: 29

How can I use java scheduledExecutor service to run a java code at a specific time of a day?

I need to run a specific java program at a particular time of the day and I need to modify the following code to make it run at a particular time of the day.

    private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public static void main(String args[]) {
    final Runnable beeper = new Runnable() {
        public void run() {
            System.out.println("beep");
        }
    };

    final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 1, SECONDS);
    scheduler.schedule(new Runnable() {
        public void run() {
            beeperHandle.cancel(true);
        }

    }, 60 * 60, SECONDS);
}

Upvotes: 1

Views: 180

Answers (2)

HuTa
HuTa

Reputation: 178

You have to use ScheduledExecutorService ? It's not good for scheduling tasks at specific time. It's ment to be used for delayed/repeated actions. Have you seen Quartz ? Documentation has nice examples and library allows you to be very specific about time of task.

//edit: Here you have example implementation example: https://www.mkyong.com/java/quartz-2-scheduler-tutorial/ You can use: https://hc.apache.org/httpcomponents-client-ga/examples.html It allows to do simple calls. Like this:

HttpGet httpGet = new HttpGet("http://somesite.com");
BasicHttpClientConnectionManager manager = new BasicHttpClientConnectionManager();
HttpClient client = new MinimalHttpClient(manager);
client.execute(httpGet);

Put this code into job and it should work.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

You can check actual time in beeper each time it is invoked and beep only at requested hosr:

 public void run() {
     if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == REQUESTED_HOUR) {
            System.out.println("beep");
     }

Upvotes: 0

Related Questions