Run once while loop

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Apr 4 09:42:07 EDT 2012


On Wed, Apr 4, 2012 at 9:21 AM, Anatoli Hristov <tolidtm at gmail.com> wrote:
> I thing the best will be if I use hundreds of the seconds to print the
> message.
>
> for example at 12:00:00:10, but unfortunately I cant see that I can use
> hundreds of the seconds.
>
> Does anyone knows if I can use it ?
>
> Thanks
>
> Anatoli
>
>

Your proposed solution is one of those hacks that will cause your
program to fail if we get better machines that could run that loop
twice in 1/100th of a second. "When the only tool you have is a
hammer, every problem looks like a nail". You need to add more tools
to your toolbox than an infinite loop. If your problem is that you
want to trigger an event at a specific time, John's answer is the
correct one. If your entire program is just this recurring task, use
your OS's task scheduler (Task Scheduler for Windows, Launchd for Mac
OS X, and Cron for other *nixes).

> On Wed, Apr 4, 2012 at 2:25 PM, John O'Hagan <research at johnohagan.com>
> wrote:
>>
>> On Tue, 3 Apr 2012 23:00:22 +0200
>> Anatoli Hristov <tolidtm at gmail.com> wrote:
>>
>> > On 03 Apr 2012, at 22:45, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> >
>> > > On Tue, Apr 3, 2012 at 2:36 PM, Anatoli Hristov <tolidtm at gmail.com>
>> > > wrote:
>> > >> Hi,
>> > >>
>> > >> I'm trying to do a while loop with condition of time if time is
>> > >> 12:00:00 print text, but for this one second the text is printed at
>> > >> least 50 times, how can I print only once?
>> > >
>> > > Set a flag when you print the text to indicate that you've already
>> > > printed it, and don't print it again if the flag is set.  When it's no
>> > > longer 12:00:00, reset the flag.
>> > >
>> > > That said, a busy while loop is probably the wrong way to do this,
>> > > because it will run your CPU at 100%.  Better would be to put the
>> > > thread to sleep with time.sleep() calls or a real event loop with a
>> > > timer event.
>> > >
>> > > Cheers,
>> > > Ian
>> >
>> > Thank you Ian,
>> >
>> > what if I wait for other conditions if I use time.sleep for 1 sec? it
>> > means that all the program is sleeping for a sec.
>> >
>>
>> If I understand correctly, you don't want the whole program to sleep. If
>> that's the case, you could use threading.Timer, for example:
>>
>> import threading, time
>>
>> def twelve():
>>    print("It's twelve o'clock")
>>
>> local_secs = (time.time() - time.timezone) % (24 * 60 * 60)
>> secs_till_12 = 12 * 60 * 60 - (local_secs % (12 * 60 * 60))
>>
>> wait_till_12 = threading.Timer(secs_till_12, twelve)
>> wait_till_12.start()
>>
>>
>> Regards,
>>
>> John
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list