2

If I wanted to do a command at a random time between two times how would I do this?

For example, send the following request at a random time between 10 seconds and 60 minutes?

import requests

r = requests.get('https://api.github.com/events')
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Proletariat
  • 213
  • 5
  • 10

3 Answers3

4

The easiest implementation would be to make your program sleep for a random amount of time between 10 and 3600 seconds.

You can use the time.sleep() method to make your program pause and the random.randint(x, y) method to generate a random number between x and y

import time, random, requests

time.sleep(random.randint(10, 3600))
r = requests.get('https://api.github.com/events')
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • This would only do the request once, correct? Is there a way for it to keep doing the requests until I stop it? – Proletariat Sep 28 '17 at 13:18
  • That depends on how you'd like to stop it, but yes this will only make the requests call once – Alan Kavanagh Sep 28 '17 at 13:19
  • If you'd like to keep this running multiple times, you will need to create a loop and add some extra logic depending on how you'd like the script to stop – Alan Kavanagh Sep 28 '17 at 13:25
1

You can use the random module

import random
import time

secondstowait = random.randint(10, 60)
minutestowait = random.randint(0, 59) * 60 # converts minutes to seconds

time.sleep(secondstowait + minutestowait)

the sleep() function from time module obviously stops your program for the requested amount of seconds

gogaz
  • 2,323
  • 2
  • 23
  • 31
1

While there are many ways of doing this, you could try to use full featured libraries to avoid reinventing the wheel and that can fulfill more complex requirements. Since your example snippet is python, please take a look at Simpy.

It is an excellent full featured library things like your example to more complex full featured simulations.

Luv
  • 386
  • 4
  • 15