How can I update my data automatically in Kivy? - python

I have a code block in my class
def datas(self):
source = requests.get("http://150.150.150.150/tek.json").json()
return source
My program uses this data and this data is updated in that server everyday at 12:05 AM.
When i run app at 12:00 and if i wait untill 12:10 the datas is not updated in my app.
Only if i restart the app then new data pulls from my app.
I used While True and sleep for 10 but this caused the program to wait every 10 seconds to run.
How can i fix this issue. Should i use Clock Schedule? I don't know how to use. Could you please help me? I want to apdate data in every 10 seceonds so new datas can seen on the screen.
Thanks very much.

I think in this case what could be helpful is an asyncio library. It would the While True loop to run every 10 seconds without freezing the whole program.
Here is an example:
https://github.com/kivy/kivy/blob/master/examples/async/asyncio_basic.py?fbclid=IwAR0Ae1UhdZL57ytHdVzpXYiPUnxE1c5si6RWnYQjo5l_N-Wm3MTNbGJDsok
And if that does not work for you there are plenty videos on YTB from "Tech with Tim" for example that shows you how to set methods in asyncio .

Using the Clock object looks like the easiest way to solve your problem. To execute your function retrieving data every 10 seconds, you can use:
from kivy.clock import Clock
def datas(self):
source = requests.get("http://150.150.150.150/tek.json").json()
return source
Clock.schedule_interval(datas, 10)
However, I don't really get why you want to retrieve the data every 10s if you know it's updated only once per day. To me, it would make more sense to schedule the Clock for every 60s, check whether it's 12:06 for instance, and only do the request if it's the case (otherwise do nothing)

Related

Best way to constantly check for scheduled events on a website

So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin their account.
I'm already using SQLite so I'm going to create a table in there where scheduled events will be defined.
What I'm wondering is what is the best way to constantly check these scheduled events, it may also be important to note I want to check at least every hour. My immediate thought was creating a separate thread and running a function on there with a while loop in it which will constantly run a chunk of code with a time.sleep(3600) at the end of the function, like this:
def check_events(self):
while True:
# code
time.sleep(3600)
I'm not sure though if this is the most efficient way of doing it.
That function currently is inside my website code class hence the self, is that something I need to put on the outside or no?
I would either create a cron job on your server (which is the most straightforward)
or use a schedule module to schedule your task, see example:
import time
import schedule
from sharepoint_cleaner import main as cleaner
from sharepoint_uploader import main as uploader
from transfer_statistics import main as transfer_stats
schedule.every(1).hours.do(uploader)
schedule.every(1).hours.do(transfer_stats)
schedule.every().sunday.do(cleaner)
while True:
schedule.run_pending()
time.sleep(10)
https://github.com/ansys/automatic-installer/blob/4d59573f8623c838aadfd49c312eeaca964c6601/sharepoint/scheduler.py#L3

Python kivy clock -- how to get intervals to time from the end of the previous iteration?

I'm trying to set up Clock.schedule_interval using Kivy in Python.
The relevant code snippet looks something like this:
event = Clock.schedule_interval(lambda x: refresh(),20)
The refresh function usually takes approx 10 seconds to run, but occasionally it will take 60 seconds.
I want the 20 second wait to occur between each iteration of refresh.
That is, I'd like it to work like this:
Refresh. Wait for it to complete (approx 10-60 seconds).
After completion, wait 20 seconds.
Refresh again. Etc.
It seems like the default behavior is to start the 20 second timer when refresh starts, not when it completes. Is there a way to change this?
Also, if refresh is taking 60s and the 20s interval passes, will it start refresh a second time even though refresh is ongoing? Will it queue another thread? If so, is there a way to tell it "If refresh hasn't completed yet, skip this iteration and wait another interval"?
Thanks for any help you can offer!
Use Clock.schedule_once() to run refresh() the first time, then add a Clock.schedule_once() at the end of the refresh() method to schedule itself again in 20 sec.

Executing code after waiting for time in background (Python)

I'm making a personal assistant like Google Assistant or Siri, and I want the user to be able to set reminders. For example, if they type "Remind me to wash the dishes at 5pm" I would like it to pop up later and remind them. However I also want code to be able to run while waiting, so you could set multiple reminders or check the weather.
time.sleep simply stops the program. I'm pretty sure there's a way to do it with threads but I'm not sure how. Please help!
Python threading has a Timer which does exactly what you ask for:
from datetime import datetime
from threading import Timer
def create_notification(time, name):
delay = (time - datetime.now()).total_seconds()
Timer(delay, show_notification, args=[name]).start()
def show_notification(name):
print(f'notification: {name}!')
create_notification(datetime(2034, 1, 1), 'Hello future!')
One thing to watch out for is this approach creates a single thread for each event (which doesn't scale well for lots of events). This also suffers from the problem that if the user closes your program, your program crashes, computer shuts down, power loss, etc. you lose all of your notifications. If you need to handle this, then save them to a file. If you need the notifications to show up even when your program isn't running look into solutions provided by the OS like cronjobs.

Python chat server when can't guarantee page not reset?

I'm relatively new to Python, cgi, and passenger-wsgi, so please bear with me.
I set up a python script that's not much more than
import time
startTime = time.time()
def main():
return time.time()-startTime
.. just so I know how long the passenger server has been running. I did this a few days ago, but it's only at about 12 minutes now.
Keeping track of state isn't important for any of the scripts I currently have, but I'm planning on writing a simple chat page. Keeping track of the various users online and the chat groups will be very important, and I wouldn't want everything to be reset every 12 minutes.
What can I do about this?
My only thought is to store any necessary variables inside an object, then serialize that object and store it in a file every time I change it so that if the server restarts again I still have everything. Is this normally how it's done?

How to use thread in Django

I want to check users' subscribed dates for certain period. And send mail to users whose subscription is finishing (ex. reminds two days).
I think the best way is using thread and timer to check dates. But I have no idea how to call this function. I don't want to make a separate program or shell. I want to combine this procedure to my django code. I tried to call this function in my settings.py file. But it seems it is not a good idea. It calls the function and creates thread every time I imported settings.
That's case for manage.py command called periodically from cron. Oficial doc about creating those commands. Here bit more helpful.
If you want something simpler then django-command-extensions has commands for managing django jobs.
if you need more then only this one asynchronous job have a look at celery.
using Django-cron is much easier and simple
EDIT: Added a tip
from django_cron import cronScheduler, Job
class sendMail(Job):
# period run every 300 seconds (5 minutes)
run_every = 300
def job(self):
# This will be executed every 5 minutes
datatuple = check_subscription_finishing()
send_mass_mail(datatuple)
//and just register it
cronScheduler.register(sendMail)

Categories