Time as stopping condition of infinite loop

后端 未结 5 1798
我在风中等你
我在风中等你 2021-01-29 02:11
# run infinitly
while(True):

  done = False;

  while(not done):
    #Do Stuff
    #Main Program

    #stopping condition of inner while loop
    if datetime.datetime.n         


        
5条回答
  •  隐瞒了意图╮
    2021-01-29 02:47

    This does not directly answer the question, but just in case all you want to achieve in the first place is to run some python code every (say) 10 minutes, you'd better implement this using cron.

    I assume you so far have a script that is somehow started at boot time. It mainly consists of an infinite loop, a main procedure, and a wait-until-next-execution-time component. For example like the following:

    """ my_first_daemon.py
        does something everytime the datetime minute part is fully divisible by ten
    """
    
    while True:
        # do something at 00,10,20,30,40,50 (minutes) every hour
        print "Hello World!"
        # wait until the next execution time
        wait_until_next_ten_minute_time()
    

    If this is indeed the case I'd suggest to move the main section of your script to a separate script. For example like the following:

    """ my_first_cronjob.py
        is run by cron everytime the datetime minute part is fully divisible by ten
    """
    
    # do something at 00,10,20,30,40,50 (minutes) every hour
    print "Hello World!"
    

    The you go ahead and add to your crontab (use the command crontab -e to add the entry to that user's crontab that shall run the script, also have a look at the manpage). For example like this:

    # Example of job definition:
    # .---------------- minute (0 - 59)
    # |  .------------- hour (0 - 23)
    # |  |  .---------- day of month (1 - 31)
    # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
    # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
    # |  |  |  |  |
    # *  *  *  *  *     command to be executed
    
    # example entry:
    # (divide minute-star by 10 to get it run every 10 minutes) 
    */10 *  *  *  *     python /path/to/my_first_cronjob.py
    

    After the edit you should notice a message like crontab: installing new crontab and then you're done. Just wait and have a look if it works.

    Some things to note as well:

    • The script's output to stdout and stderr are sent to you by mail after termination. Have a look at tail -f /var/mail/moooeeeep (specify your username). You can also configure Thunderbird to fetch these mails, in order to inspect them easier.
    • The corresponding Wikipedia page is a very good source of information for further details.
    • If you need to keep state information between independent runs of the script, consider using a configuration file to store this state information, e.g., using pickle, shelve, sqlite, whatever.

提交回复
热议问题