简体   繁体   中英

How to execute a task between a certain time period regardless of the Date

I have a Thread in my application which runs continuously till the application is stopped .

I want to change its behavior to run only during the time period from 9 AM to 6 PM regardless of the Date

As per the suggestion below , i have done this please let me know if this has got any negative impact .

package com;

import java.util.Calendar;

public class ContinousThread extends Thread {
    public void run() {

        while (true) {
            Calendar c = Calendar.getInstance(); // is automatically initialized to
            int hour = c.get(Calendar.HOUR_OF_DAY);
            boolean run = hour >= 9 && hour < 18;
            if (run) {
                doSomething();
            } else {
                System.out.println("No");
            }
        }
    }

    public void doSomething() {
        // actual task
    }

    public static void main(String args[]) {

        ContinousThread ct = new ContinousThread();
        ct.start();
    }
}

Use the Calendars get(field) method to get the hour:

 Calendar c = Calendar.getInstance(); // is automatically initialized to current date/time
 int hour = c.getField(Calendar.HOUR_OF_DAY);
 boolean run = hour >= 9 && hour < 18;

i have done this please let me know if this has got any negative impact

There is.

boolean run = hour >= 9 && hour < 18;
if (run) {
    doSomething();
} else {
    System.out.println("No");
}

When run is false you have a "busy loop" . This will make the cpu busy, very busy. And also print tons of No on console.

One approach is to put a sleep in the else block. You can probably sleep for a long time at 18:00 , compute how far you are from the next 9:00 and sleep for that much (or a little less)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM