How to run a python script twice randomly in a day?

Cameron Simpson cs at zip.com.au
Mon May 20 09:40:02 CEST 2013


On 20May2013 09:47, Avnesh Shakya <avnesh.nitk at gmail.com> wrote:
| On Mon, May 20, 2013 at 9:42 AM, Cameron Simpson <cs at zip.com.au> wrote:
| > On 19May2013 20:54, Avnesh Shakya <avnesh.nitk at gmail.com> wrote:
| > |    How to run a python script twice randomly in a day? Actually
| > | I want to run my script randomly in a day and twice only. Please
| > | help me.. how is it possible.
| >
| > Do you mean "run twice a day, each at random times"?
| >
| > If so, do the obvious: at midnight, pick two random times. Sleep
| > until the first time, run the script, sleep until the second time,
| > run the script.
| >
| > There are various ways to do the sleeping and midnight bits; they're
| > up to you.
|
| Thanks, Can you mail documentation or link for it? I am totally new for it.

1: Please reply on-list; you asked the list, the discussion should
   remain there. I have added the list to the CC line.

2: Please don't top-post. Quote only the relevant bits of the
   previous message and reply below. If the message is long, do
   that in pieces. [quote] reply [quote] reply. Like a conversation.

Now, to your questions.

A UNIX user would use "cron" to schedule the midnight job and from
the midnight job then probably use "at" to schedule the other jobs
to run at specific times. See "man 1 crontab", "man 5 crontab" to
submit the cron jobs and "man at" to submit the once off jobs.

UNIX means Linux, Solaris, AIX, any of the BSDs (includes MacOSX),
etc.

You could a small python script for the midnight job, and it would
submit the "at" jobs. See the "random" module to compute a pseudorandom
number (and thus a random time), the "datetime" module to compute
the dates and times from that number, and the "subprocess" module
to submit the "at" job for the chosen run times. The modules are
here:

  http://docs.python.org/3/py-modindex.html

That presumes python 3; if you're using python 2 the docs for that
are available at the same web site.

You don't need to use "at". Your midnight job could just compute
the time in seconds to each job time, then use the "time.sleep"
function to delay until then. See the "time" module at the above
link.

Nobody on this list will write your program for you.

Attempt to write the program, then come to the list with your attempt
and any problems. People will help if you've made an initial effort,
and continue to try. This question has the "feel" of a homework
question; the point of homework is for you to learn by solving a
problem yourself. It is fine to seek help, but you must make the
effort yourself.

Come back with specific questions.

Cheers,
--
Cameron Simpson <cs at zip.com.au>

I'm not weird; I'm gifted.



More information about the Python-list mailing list