APScheduler Running 'date' early using Python with Selenium - python

I am trying to use APScheduler to automate a function call. It is supposed to read a date from a website I scrape, and then at a certain time relative to that date call the function (2 minutes before). The code for this portion of the project is here:
for mtp, url, track in zip(mtp_num_final, url_list, race_list):
scheduled_time = datetime.now() + relativedelta(minutes =+ (mtp - 2))
print(scheduled_time.strftime('%m-%d-%Y %I:%M%p'))
scheduler.add_job(two_minute_scrape(url, track, 5), 'date', scheduled_time)
The basic gist of the above code is that race_list and and url_list hold data which the two_minute_scrape function needs. I get the amount of minutes + 2 that I want to wait from mtp num final. When I run this code, the printed out date is correct - it knows exactly when I want to run the code, but then it IMMEDIATELY runs two_minute_scrape instead of waiting for that time. Is there anyway to solve this?
Thanks!

Related

I'm trying to send a message using telebot python every month in 28th [duplicate]

I have a script that runs every 30 minutes but there is a section I just want to run on the first of the month at 2:00 am. I am using schedule in Python and I can't figure out how to set it for day 1 of the month.
month doesn't seem to be in the defined parameters of schedule to do something like schedule.every().month.at("02:00").do(job2)
Any suggestions? I am using python 2.7
Simplified code:
from safe_schedule import SafeScheduler
import time
def job():
print "I'm working...",
return
def scheduler():
# Schedule every30min routines
print 'Starting Scheduler'
scheduler = SafeScheduler()
scheduler.every(30).minutes.do(job)
#scheduler.every().month.at("02:00").do(job2)
while True:
scheduler.run_pending()
time.sleep(1)
if __name__ == '__main__':
scheduler()
The main contributor of the library discourages this sort of thing, see https://github.com/dbader/schedule/issues/73#issuecomment-167758653.
Yet, if one insists, one can schedule a daily job but run it only if it's the 1st of the month.
from datetime import date
from safe_schedule import SafeScheduler
def job2():
if date.today().day != 1:
return
# actual job body
scheduler = SafeScheduler()
scheduler.every().day.at("02:00").do(job2)
Another alternative is described in one of the issue comments https://github.com/dbader/schedule/issues/73#issuecomment-356769023.
EDIT :
They mention something about this in many issues of the project but a clean solution doesn't seem to exist yet. Also the whole project doesn't seem to be active anymore so I don't think this feature will be implemented anytime soon.
IMO you need to check manually if the current day is the first day of the month in your job in order to do this.
ORIGINAL ANSWER (which is wrong):
I've looked at the documentation and you are right, there isn't any mention of month:
https://schedule.readthedocs.io/en/stable/api.html#schedule.Scheduler
But there is an issue opened on the project that mentions just that:
https://github.com/dbader/schedule/issues/73
You can do this:
scheduler.every().day.if(lambda d,t: d.day == 1 and t.hour == 2).do(x)
I didn't see any mention of Windows Task Scheduler, here, but that could definitely work for you, if you are on Windows, of course.
https://www.digitalcitizen.life/how-create-task-basic-task-wizard

Precisely simulating an xbox controller for Unity game

I'm trying to simulate a controller via python but having issues with timing.
I've successfully implemented reading the inputs into a dictionary, and then collecting all of them into a list. I know that the game(in Unity) doesn't recognise inputs faster than 0.2s. Using the following function, I've managed write at 0.2s with an error of less than 0.001s with the following function:
def feed(line: list, interval: float = 0.1.99):
start = time_ns()
wait_ns = interval * 10**9
for moment in list:
while (time_ns() < start + wait_ns):
pass
for key, val in moment:
controller.set_value(key, val) #this feeds the keys to the game via pyxinput.
I'm sampling the input using a similar function as above. But yet, I'm not getting the correct behaviour, it seems to be a timing problem. I tried reading the synthetic inputs, and they're being input with the correct timing, i.e. the interval that I pass in(and the aforementioned error).
For reference, the following, hard coded input works correctly.
controller.set_value('AxisLy', -1) #push the stick down
sleep(0.2)
controller.set_value('AxisLy', 0) #return it to neutral
I'm at my wit's end after fighting with this for the past few days. So, any ideas on what could be going wrong, or how I may debug it?
Instead of hard coding in a sleep interval, try using Invoke() or a coroutine. I find them very simple, useful and easy to understand when you're wanting to wait a certain period of time. Alternatively, use Time.time to track the start time of a button press, and then check if (Time.time >= startTime + interval) for system clock time.
Sorry for the C#, it's what i'm more familiar with. But you should be able to get the gist of it.

How to update a timestamp taken from server?

I have a very simple Python script in which I'm trying to print an updated timestamp (taken from a server by APIs) every n seconds.
After importing a custom module (FinexAPI) and the time module:
import FinexAPI
import time
and setting up the variable to get the server timestamp:
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
if I perform:
print when
I'm getting the timestamp up to date. If I perform it again, I can see a new updated timestamp. Untill now there's no problem at all.
Now let's suppose I need to perform an "updated timestamp print" every 5 seconds:
def getNewTimestamp():
print when
time.sleep(5)
while True:
getNewTimestamp()
But with this code I'm getting the same timestamp every 5 seconds. I suppose the problem is that I'm defining when outside the getNewTimestamp function, so it basically keeps printing the same non-updated timestamp. But even if I define it inside the function I still get no update on the timestamp.
Another thing I'm thinking about is that while loop is not the best choice in this scenario, but that would be another story (I think...). Can someone help me figuring out what am I doing wrong and what is the best way to obtain and print the updated timestamp every 5 seconds?
You have to call the API in the loop:
def getNewTimestamp():
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
print when
while True:
getNewTimestamp()
time.sleep(5)

How to set a cron job on Skygear to run every 12 hours?

Trying to set a cron job on my Skygear python cloud code, but not sure what I should enter in the decorator. I only know that it will work for units in second, but how to schedule a job to run every 12 hours? It is hard to calculate the seconds every time.
My code is like this, the function is to call a POST request:
#skygear.every('#every 43200s')
def post_req():
print ('scheduled to run every 12 hours')
url = myurl
ref = something
r = requests.post(myurl, data = {'token':some_token, 'ref':something})
It actually works but is there some ways to write in a better format?
It seems like skygear.every also accepts crontab notation… so 0 */12 * * * could also do the trick.
Edit: Reading the robfig/cron docs, the best solution would actually be just #every 12h

Python script with cron only finished the first loop

I have a python script which runs a for loop. I made it executable and put it in a cron job.
It posts a few tweets on twitter. For each loop, it sleeps a few seconds with random times.
However, it appears it only runs the very first loop and then stops. Every time, I only got ONE tweet. I could not figure out why.
Here is the core part of the code.
def post_message(url):
d = parse(url)
entries = d.entries
for entry in entries:
str = entry.title
tweet(str)
t = random.randint(start, stop)
time.sleep(t)
This is how I set it in cron.
0 23 * * * /home/demo/post_message.py
It only post the very first one and then stops. I am wondering if the time.sleep function stops the rest loops in cron?
Thanks.
Have you tried to run this python script from shell?
Is there any exception (Like you posted too frequently led the script to a 403 page which keeps the function from finding any appropriate html element) generated in 2nd tweet() function?

Categories

Resources