Package: aioskd
aioskdAsynchronous Background Task SchedulerProject Overviewaioskd is a powerful Python library designed to handle the execution of background tasks asynchronously and at scheduled intervals. It provides an efficient and flexible scheduler, making it effortless to integrate asynchronous background processing into your Python projects.As applications grow more complex, certain tasks need to be executed in the background without affecting the responsiveness of the main application. AIOSKD is the perfect solution for such scenarios, as it allows you to offload these tasks to asynchronous workers, ensuring smooth execution and a better user experience.FeaturesAsynchronous execution of background tasksCustomizable scheduling of tasks at specified intervalsEasy-to-use API for integrating with your Python projectsLightweight and efficientInstallationYou can installaioskdusing pip:pipinstallaioskdUsageCreating the SchedulerTo get started, import the necessary modules and create an instance of theSchedulerclass:fromaioskdimportSchedulerskd=Scheduler()Scheduling TasksScheduling Tasks with Decorators (Existing Method)You can schedule tasks using the schedule decorator as shown below:importdatetimeimportasyncio@skd.schedule(interval=datetime.timedelta(seconds=1))asyncdeftask_one():print("Task One - Hello world!")awaitasyncio.sleep(2)# Simulate some async work taking 2 seconds@skd.schedule(interval=datetime.timedelta(seconds=5))asyncdeftask_two():print("Task Two - I'm running every 5 seconds!")awaitasyncio.sleep(1)# Simulate some async work taking 1 secondScheduling Tasks without Decorators (New Method)Alternatively, you can also register tasks without using decorators. Here's how you can do it:importdatetimeimportasynciofromaioskdimportSchedulerskd=Scheduler()asyncdeftest_task(name:str,age:int=25):print(f"Hello{name}with age{age}")skd.register_task(test_task,"John",age=30).schedule(interval=datetime.timedelta(seconds=5))skd.register_task(test_task,"Alice",age=28).schedule(interval=datetime.timedelta(seconds=2))In this example, the test_task function is registered with the scheduler using the register_task method.
You can pass the function along with its arguments to register_task, and then schedule it with the desired interval using the schedule method.Running the SchedulerTo start the scheduler and run the scheduled tasks, you can use therun()method:skd.run()Command Line UsageIf you want to run the scheduled tasks from the command line, you can use the following command:skdpath/to/file/with/tasks:obj_of_skdExamplesExample 1: Scheduling a Task to Fetch DataimportdatetimeimportasyncioimportaiohttpfromaioskdimportSchedulerskd=Scheduler()@skd.schedule(interval=datetime.timedelta(minutes=30))asyncdeffetch_data():url="https://api.example.com/data"asyncwithaiohttp.ClientSession()assession:asyncwithsession.get(url)asresponse:ifresponse.status==200:data=awaitresponse.json()# Process and store the data as neededprint("Data fetched successfully!")else:print("Failed to fetch data. Status code:",response.status)if__name__=="__main__":skd.run()In this example, thefetch_datatask is scheduled to run every 30 minutes. It sends a request to an API to fetch data and then processes the response accordingly.Example 2: Sending Scheduled Reminder Emailsimportdatetimeimportasyncioimportaiosmtplibfromemail.messageimportEmailMessagefromaioskdimportSchedulerskd=Scheduler()@skd.schedule(interval=datetime.timedelta(hours=24))asyncdefsend_reminder_email():email_content="Hello! Just a friendly reminder that your appointment is tomorrow."msg=EmailMessage()msg.set_content(email_content)msg["Subject"]="Appointment Reminder"msg["From"]="your_email@example.com"msg["To"]="recipient@example.com"asyncwithaiosmtplib.SMTP("smtp.example.com",587)asserver:awaitserver.starttls()awaitserver.login("your_email@example.com","your_email_password")awaitserver.send_message(msg)if__name__=="__main__":skd.run()This example schedules the send_reminder_email task to run once every 24 hours, sending a reminder email to a specified recipient about an upcoming appointment.Example 3: Sending Weather Update Emailsimportdatetimeimportasyncioimportaiohttpimportaiosmtplibfromemail.messageimportEmailMessagefromaioskdimportSchedulerskd=Scheduler()asyncdefget_weather_data(city:str)->dict:url=f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_OPENWEATHERMAP_API_KEY"asyncwithaiohttp.ClientSession()assession:asyncwithsession.get(url)asresponse:data=awaitresponse.json()returndataasyncdefsend_weather_email(city:str,recipient:str):data=awaitget_weather_data(city)temperature=data["main"]["temp"]description=data["weather"][0]["description"]email_content=f"Weather Update for{city}:\n\nTemperature:{temperature}°C\nDescription:{description}"msg=EmailMessage()msg.set_content(email_content)msg["Subject"]=f"Weather Update for{city}"msg["From"]="your_email@example.com"msg["To"]=recipientasyncwithaiosmtplib.SMTP("smtp.example.com",587)asserver:awaitserver.starttls()awaitserver.login("your_email@example.com","your_email_password")awaitserver.send_message(msg)print(f"Weather update email sent to{recipient}")# Register tasks with different cities and recipientstask1=skd.register_task(send_weather_email,"London",recipient="recipient1@example.com")task1.schedule(interval=datetime.timedelta(hours=1))task2=skd.register_task(send_weather_email,"New York",recipient="recipient2@example.com")task2.schedule(interval=datetime.timedelta(hours=2))if__name__=="__main__":skd.run()This code demonstrates the use of AIOSKD to send weather updates via email.scheduleDecoratorinterval:datetime.timedeltaThe interval between which the asynchronous function should be executed.repeat:boolA flag that indicates whether the asynchronous function should be repeated or executed only once. - If set toTrue, the function will be scheduled to run repeatedly at the specified interval. - If set toFalse, the function will be executed only once.immediate:boolA flag that controls the first execution of the scheduled function. - If set toTrue, the scheduler will execute the function immediately when starting the task for the FIRST TIME, and subsequent executions will be based on the interval. - If set toFalse, the first execution will wait for the interval before running.iter_count(optional):intThe necessary number of repeats. This parameter is applicable only whenrepeatisTrue. - It specifies the maximum number of times the function should be repeated. - If not provided, the function will continue to be repeated indefinitely until the scheduler is stopped or the coroutine is cancelled.ContributingIf you'd like to contribute to this project, follow these steps:Fork the repository and create a new branch.Make your changes and test them thoroughly.Submit a pull request, explaining the changes you've made.