Results 1 to 13 of 13
  1. #1
    dcnorman07 is offline Member
    Join Date
    Jul 2008
    Posts
    6
    Rep Power
    0

    Question Sleep until a certian time of day

    I have a script that I want to run constantly, except between the hours of 11:00 pm and 6 a.m. During those times, I want the script to sleep...

    The way it is now, it checks the Hour at the beginning of each iteration and if it is not between 23 and 6, then it runs as normal, but if the Hour is between 23 and 6, it sleeps for one hour and checks again every hour until the time is not between 23 and 6, then resumes...

    I can't have it check too often because there are only so many iterations it runs through until it will stop, and then I re-start it manually (basically so I can see the progress).

    I am wanting this to be more precise...

    Is there a way instead of saying:

    Java Code:
    sleep(3600);
    to somehow tell it to sleep until 6 am, and then resume? :confused:


    A condensed version of what I have looks like this:

    Java Code:
    public void testMain(Object[] args) 
    
                {
                            Object[] objdataToPass = new Object[1];
                            objdataToPass[0] = new Integer(1);
                            int error_tally = 0;
                            for (int i = 0; i < 1000; i++)
                            {
                               Date date = new Date();
          SimpleDateFormat formatter = new SimpleDateFormat("k"); // hour 1-24
                        String time = formatter.format(date);
                        int hour = Integer.parseInt(time);
                                        if (
                                               // Current time is after 6 AM
                                               hour >= 6
                                               &&
                                               // Current time is before 11 PM
                                               hour <= 23
                                        )
                                               {
                                                    ***Run Script Here***
                                               }            
                 
                                          else
                                               {
                                                  sleep(3600);
                                                }
    Any help on getting this thing to sleep between 11 pm and 6 am would be greatly appreciated.

    Thank you!

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Take a look at Java.util.Timer and TimerTask. Design a TimerTask that does nothing but send a notify(). Place that in a Timer for a specific time then sync on the object that should get the notify and wait() on it.

  3. #3
    dcnorman07 is offline Member
    Join Date
    Jul 2008
    Posts
    6
    Rep Power
    0

    Default

    Could you give me an example.?

    I'm not sure I quite understand how to do that.... :eek:

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    Can you compute the number of millisecs from the current time to the time you want to wakeup and sleep for that duration.
    Create some kind of date object for when you want to wakeup and get out its time as long.

  5. #5
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    System.currentTimeMillis() to get the ms.
    I die a little on the inside...
    Every time I get shot.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    That's the current time. How do you get the ms for 6AM tomorrow morning?

  7. #7
    dcnorman07 is offline Member
    Join Date
    Jul 2008
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    That's the current time. How do you get the ms for 6AM tomorrow morning?
    Norm is on to something there, if I could get the number ms until 6AM from the time it enters the sleep, that would be PERFECT!

    The reason being, is that it's not always going to be exactly 11PM when the script reaches the sleep, it could be anywhere up to 11:25PM...I just don't want it to begin the loop again after 11PM, so if I could somehow calculate the number of ms until 6AM from the time it reaches the sleep, then viola! :D

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    So start looking at the various classes that will create some kind of date object, like Calendar. There'll be a method you can call to get its time in ms. Then subtract off the current time in ms.

  9. #9
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Java Code:
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    ...
    
        public void waitUntil(Date date) {
            final Object o = new Object();
            TimerTask tt = new TimerTask() {
                public void run() {
                    synchronized (o) {
                        o.notify();
                    }
                }
            };
            Timer t = new Timer();
            t.schedule(tt, date);
            synchronized(o) {
                try {
                    o.wait();
                } catch (InterruptedException ie) {}
            }
            t.cancel();
            t.purge();
        }
    
    ...

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,518
    Rep Power
    25

    Default

    masijade:
    How do you get the Date object for the wakeup time?

  11. #11
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Make one. It is simply a method to call with the date that he wants to wake as a parameter. I would assume that he would be calling it programmatically. Truth be told, I would put the time in a properties file and create the date using the current date (+1 if the time is before the current time) and the time in the properties file. I would also put an "earliest time to be called" in the same properties file, and after each "processing round" check to see if the time is equal to or after that time and then call the method using the other. In that way it is completely flexible as to the "stop" and "start" times.

  12. #12
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Here is a complete implemetation (untested):

    Java Code:
    // Properties File
    stopHour=11
    startHour=6
    Java Code:
    package bogustest;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Properties;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class NewClass {
    
        private int stopHour;
        private int startHour;
        private Timer timer = new Timer(true);  // Create just one and make it a daemon thread.
    
        public void readProperties() {
            Properties props = new Properties();
            InputStream is = null;
    
            try {
                is = getClass().getResourceAsStream("propertiesFileName");
                props.load(is);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                if (is != null) try { is.close(); } catch (IOException ioe) {}
            }
    
            if (props.entrySet().size() != 2) {
                System.err.println("Not all Properties Defined.");
                System.exit(1);
            } else {
                stopHour = Integer.valueOf(props.getProperty("stopHour"));
                startHour = Integer.valueOf(props.getProperty("startHour"));
            }
        }
    
        public void checkTime() {
            GregorianCalendar gc = new GregorianCalendar();
            int currentHour = gc.get(Calendar.HOUR_OF_DAY);
    
            if (currentHour >= stopHour) {
                if (currentHour >= startHour) {
                    gc.add(Calendar.DAY_OF_MONTH, 1);
                }
                gc.set(Calendar.HOUR_OF_DAY, startHour);
                gc.set(Calendar.MINUTE, 0);
                gc.set(Calendar.SECOND, 0);
                gc.set(Calendar.MILLISECOND, 0);
                waitUntil(gc.getTime());
            }
        }
    
        public void process() {
            while (true) {
                // run script here
                checkTime();
            }
        }
    
        public static void main(String[] args) {
            (new NewClass()).process();
        }
    
        public void waitUntil(Date date) {
            final Object o = new Object();
            TimerTask tt = new TimerTask() {
                public void run() {
                    synchronized (o) {
                        o.notify();
                    }
                }
            };
            timer.schedule(tt, date);
            synchronized(o) {
                try {
                    o.wait();
                } catch (InterruptedException ie) {}
            }
            timer.cancel();
            timer.purge();
            readProperties();
        }
    }
    Edit Again!: Oops, it should be currentTime >= startTime not <= (already corrected).

    Also, because waitUntil calls readProperties again, at the end of it, you can change the start and stop times while the program is in wait mode, and the next time it needs to wait it will use those new times.
    Last edited by masijade; 09-19-2008 at 11:31 AM. Reason: Oops. Forgot the String[] args in main declaration. ;)

  13. #13
    joostdiet is offline Member
    Join Date
    Oct 2011
    Posts
    1
    Rep Power
    0

    Default Re: Sleep until a certian time of day

    This is the most simple solution i could think of...
    set hours minutes secs on gregorian calendartime.


    Java Code:
            int hours = 21;
            int minutes = 0;
            int seconds = 0;
    
            Calendar calendar = new GregorianCalendar();
            long curTime = calendar.getTimeInMillis();
    
            Calendar calendarTime = new GregorianCalendar();
            calendarTime.set(calendar.get(calendar.YEAR), calendar.get(calendar.MONTH), calendar.get(calendar.DATE), hours, minutes, seconds);
            if (calendar.get(calendar.HOUR_OF_DAY) > hours-1){
                calendarTime.add(calendar.get(calendar.DAY_OF_MONTH), +1);
            }
            calendarTime.getTimeInMillis();
            long nextRunTime = calendarTime.getTimeInMillis();
            
            long waitTime = nextRunTime - curTime;
    Last edited by joostdiet; 10-04-2011 at 02:36 PM.

Similar Threads

  1. How to use sleep() method
    By Hasan in forum Threads and Synchronization
    Replies: 12
    Last Post: 10-06-2009, 01:25 PM
  2. Sleep in thread
    By jithan in forum New To Java
    Replies: 1
    Last Post: 08-27-2008, 02:27 PM
  3. How to use sleep() to wait for a while
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-09-2008, 06:32 PM
  4. Can't get my thread to sleep!
    By jamesfrize in forum New To Java
    Replies: 2
    Last Post: 03-25-2008, 05:14 AM
  5. How to use the sleep and thread?
    By jiuhu in forum Java Applets
    Replies: 4
    Last Post: 08-07-2007, 02:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •