Giter VIP home page Giter VIP logo

async_cron's Introduction

async_cron

Downloads PyPI version

this repo is influenced by schedule.

we supply a async scheduler and async function support

you can easily integrate this lib to you async program,with no blocking

Install


pip install async-cron

Usage examples


import asyncio

from async_cron.job import CronJob
from async_cron.schedule import Scheduler


async def test(*args, **kwargs):
    print(args, kwargs)


def tt(*args, **kwargs):
    print(args, kwargs)


msh = Scheduler(locale="zh_CN")
myjob = CronJob(name='test', run_total=3).every(
    5).second.go(test, (1, 2, 3), name=123)
job2 = CronJob(name='exact', tolerance=100).at(
    "2019-01-15 16:12").go(tt, (5), age=99)
job3 = CronJob(name='very_hour').every().hour.at(
    ":44").go(tt, (5), age=99)

job3 = CronJob(name='hour').every().hour.at(
    ":00").go(tt, (5), age=99)
job4 = CronJob(name='minute').every(1).minute.go(tt, (5), age=99)
job5 = CronJob(name='weekday').weekday(2).at("11:18").go(tt, (5), age=99)
job6 = CronJob(name='monthday').monthday(16).at("11:22").go(tt, (5), age=99)
job7 = CronJob(name='monthday').every(5).monthday(
    16).at("11:22").go(tt, (5), age=99)


msh.add_job(myjob)
msh.add_job(job2)
msh.add_job(job3)
msh.add_job(job4)
msh.add_job(job5)
msh.add_job(job6)
msh.add_job(job7)

# jobload is only a special job,who gen jobs from config
# below means, this job load will check every 1 second for cron updates
# if any updates found,new job will be add to scheduler
# you dont have the direct way to delete jobs
# but you can modify the crons total_times to 0 or 1 to delete it
# by default,FileJobLoader use MultiThread,you can use MultiProcess by add
# thread=False

f_cron = FileJobLoader(name='f_cron', file_path='t_cron', log_path='.',thread=False)

fjob = CronJob(name='fjob', run_total=1).every(
    1).second.go(f_cron.run, msh)

msh.add_job(fjob)


loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(msh.start())
except KeyboardInterrupt:
    print('exit')

cron file useage:

parameter separate by blank.in item separate by comma

cron name job env run_times
*/1,*,*,*,* test /bin/python,tt.py aa=123,bb=345 10

example as follow:

common cron

*/1,*,*,*,* test /bin/python,tt.py aa=123,bb=345 1

delete cron */1,*,*,*,* test /bin/python,tt.py aa=123,bb=345 0

cron only support: *,10,*/10 format. which fulfills mostly screen

License

The async_cron is offered under MIT license.

async_cron's People

Contributors

aohan237 avatar jimnero009 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

async_cron's Issues

Error while running job using cron time format

I have this exact usecase mentioned here: https://stackoverflow.com/questions/47356453/python-schedule-jobs-with-different-timezones

I am trying to use cron time format to run a task every day 8 PM, but getting errors.

Here is the code:

import asyncio
import logging

from async_cron.job import CronJob
from async_cron.job_loader import JobLoader
from async_cron.schedule import Scheduler

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)10s - %(message)s')
logger = logging.getLogger(__name__)


async def test(*args, **kwargs):
    logger.info(f'Args: {args}, Kwargs: {kwargs}')


async def main():
    msh = Scheduler(locale="en_us", check_interval=1)
    task = loop.create_task(msh.start())
    await asyncio.sleep(0.1)
    j_loader = JobLoader(log_path='.')
    # minute, hour, day, week, month, year
    job = j_loader.parse_cron('*,20,*,*,*,*')  # Need to run a task every day 8 PM, how to specify format?
    if job is not None:
        # job.tz = 'Asia/Kolkata'              # Want to run the task based on custom timezone, modifying this way will it work?
        logger.info(job)
        job.go(test, (1, 2, 3))

    msh.add_job(job)
    logger.info(f'Jobs: {msh.jobs}')
    await task


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Here is the error:

2019-10-30 21:39:34,347 -      DEBUG - Using selector: SelectSelector
2019-10-30 21:39:34,457 -      ERROR - Expected an ISO 8601-like string, but was given '*-*-*                     20:*'. Try passing in a format string to resolve this.
Traceback (most recent call last):
  File "D:\Projects\Experiments\venv\lib\site-packages\async_cron\job.py", line 189, in at
    arrow_time = arrow.get(time_string)
  File "D:\Projects\Experiments\venv\lib\site-packages\arrow\api.py", line 21, in get
    return _factory.get(*args, **kwargs)
  File "D:\Projects\Experiments\venv\lib\site-packages\arrow\factory.py", line 188, in get
    dt = parser.DateTimeParser(locale).parse_iso(arg)
  File "D:\Projects\Experiments\venv\lib\site-packages\arrow\parser.py", line 121, in parse_iso
    datetime_string
arrow.parser.ParserError: Expected an ISO 8601-like string, but was given '*-*-*                     20:*'. Try passing in a format string to resolve this.
2019-10-30 21:39:34,494 -       INFO - 7006048c-fb98-11e9-a626-20791861ca69 parse datetime error
2019-10-30 21:39:34,494 -       INFO - 7006048c-fb98-11e9-a626-20791861ca69-1:None-(None, None)            -None-None
2019-10-30 21:39:34,494 -       INFO - Jobs: {'7006048c-fb98-11e9-a626-20791861ca69': 7006048c-fb98-11e9-a626-20791861ca69-1:None-(None, None)            -None-None}
2019-10-30 21:39:35,353 -       INFO - runing:7006048c-fb98-11e9-a626-20791861ca69:just now
2019-10-30 21:39:35,353 -      ERROR - shift() keywords must be strings
Traceback (most recent call last):
  File "D:\Projects\Experiments\venv\lib\site-packages\async_cron\schedule.py", line 25, in start
    await self.check_jobs()
  File "D:\Projects\Experiments\venv\lib\site-packages\async_cron\schedule.py", line 55, in check_jobs
    job.run()
  File "D:\Projects\Experiments\venv\lib\site-packages\async_cron\job.py", line 168, in run
    self.gen_next_run()
  File "D:\Projects\Experiments\venv\lib\site-packages\async_cron\job.py", line 173, in gen_next_run
    self.next_run = self.last_run.shift(**{self.unit: self.interval})
TypeError: shift() keywords must be strings
2019-10-30 21:39:35,365 -       INFO - error occurs,exit
2019-10-30 21:39:35,365 -       INFO - Args: ((1, 2, 3),), Kwargs: {}

Set log level should be removed

The get_logger function is overriding the log level every time you create a CronJob or Scheduler. This part should be removed to allow the user select his desired log level. Another option could be using a singleton for get_logger, then the user don't need to override the log level every time creates a new CronJob. Anyways the log level is designed to be used for the final user, you should use it to print diferent level messages, but the user needs the ability to select which ones wants to print.

How do you use this with a Tornado application

How do you use it in a Tornado application?

Using :

loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(msh.start())
except KeyboardInterrupt:
    print('exit')

Blocks my application.

Scheduling Job at specific time feature is not working properly

"""
Version Details:
    Python 3.7.4
    async-cron==1.6.1
"""
import asyncio
import sys

from async_cron.job import CronJob
from async_cron.schedule import Scheduler


def test(name):
    print(name)


sch = Scheduler(locale='en', check_interval=1)
job1 = CronJob()
job1.at('2020-01-18 22:34').go(test, ('test_job',))  # Does not get triggered when time is elapsed
job2 = CronJob()
job2.at('22:34').go(test, ('test_job',))  # Job triggered but fails with: TypeError: shift() keywords must be strings


if __name__ == '__main__':
    try:
        print('Start')
        sch.add_job(job1)
        sch.add_job(job2)
        loop = asyncio.get_event_loop()
        loop.run_until_complete(sch.start())
    except KeyboardInterrupt:
        sys.exit()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.