├── test ├── simple.ipynb ├── python_test (every day at 1pm).py ├── python_test (every day at 1.00pm).py ├── python_test (every day at 1.00pm).py.output.txt ├── .DS_Store └── hello_world (every day at 5.00pm).ipynb ├── jupyter-cron ├── __init__.py └── __main__.py ├── .gitignore ├── LICENSE ├── README.rst └── setup.py /test/simple.ipynb: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /jupyter-cron/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/python_test (every day at 1pm).py: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | -------------------------------------------------------------------------------- /test/python_test (every day at 1.00pm).py: -------------------------------------------------------------------------------- 1 | print("hello world") 2 | -------------------------------------------------------------------------------- /test/python_test (every day at 1.00pm).py.output.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /test/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quocble/jupyter-cron/HEAD/test/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | MANIFEST 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | env 39 | env3 40 | __pycache__ 41 | venv 42 | 43 | .cache 44 | docs/_build 45 | -------------------------------------------------------------------------------- /test/hello_world (every day at 5.00pm).ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "hello world\n" 13 | ] 14 | } 15 | ], 16 | "source": [ 17 | "print(\"hello world\")" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "metadata": { 24 | "collapsed": true 25 | }, 26 | "outputs": [], 27 | "source": [] 28 | } 29 | ], 30 | "metadata": { 31 | "kernelspec": { 32 | "display_name": "Python 3", 33 | "language": "python", 34 | "name": "python3" 35 | }, 36 | "language_info": { 37 | "codemirror_mode": { 38 | "name": "ipython", 39 | "version": 3 40 | }, 41 | "file_extension": ".py", 42 | "mimetype": "text/x-python", 43 | "name": "python", 44 | "nbconvert_exporter": "python", 45 | "pygments_lexer": "ipython3", 46 | "version": "3.6.1" 47 | } 48 | }, 49 | "nbformat": 4, 50 | "nbformat_minor": 2 51 | } 52 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Quoc Le 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Jupyter cron 2 | ============ 3 | 4 | Simple clock/cron process that monitors a specific directory and run jobs based on its filename. 5 | 6 | Currently filename with this pattern is supported: 7 | 8 | (every X at time) where 9 | 10 | **X** is ['day', 'monday', 'tuesday', 'wednesday','thursday', 'friday','saturday','sunday'] 11 | 12 | **time** is either in short form without minutes like 5PM or long form with minutes, 5:00PM 13 | 14 | 15 | For example: 16 | 17 | **notebooks/generate_model (every day at 5pm).ipynb** will trigger `jupyter nbconvert` to run every day at 5pm. 18 | 19 | **scripts/gen (every monday at 12pm).py** will trigger `python scripts/gen....py` to run. 20 | 21 | 22 | Features 23 | -------- 24 | 25 | - Simple to use 26 | - Integrates well with Jupyter 27 | - Tested on Python 3.6 28 | 29 | Usage 30 | ----- 31 | 32 | .. code-block:: bash 33 | 34 | usage: jupyter-cron [-h] [-d] glob 35 | 36 | Scans for file to run on a schedule based on its name 37 | 38 | positional arguments: 39 | glob specify glob to search eg. test/**/*.ipynb 40 | 41 | optional arguments: 42 | -h, --help show this help message and exit 43 | -d, --daemonize daemonize the process 44 | 45 | Meta 46 | ---- 47 | 48 | Quoc Le - `@realQuoc `_ - quocble@gmail.com 49 | 50 | Distributed under the MIT license. See ``LICENSE.txt`` for more information. 51 | 52 | https://github.com/quocble/jupyter-cron 53 | http://rst.ninjs.org/ 54 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | Publish a new version: 3 | $ git tag X.Y.Z -m "Release X.Y.Z" 4 | $ git push --tags 5 | $ pip install --upgrade twine wheel 6 | $ rm dist/* && python setup.py sdist bdist_wheel 7 | $ twine upload dist/* 8 | """ 9 | import codecs 10 | import os 11 | import sys 12 | from setuptools import setup 13 | 14 | 15 | SCHEDULE_VERSION = '0.1.5' 16 | SCHEDULE_DOWNLOAD_URL = ( 17 | 'https://github.com/quocble/jupyter-cron/tarball/' + SCHEDULE_VERSION 18 | ) 19 | 20 | def read_file(filename): 21 | """ 22 | Read a utf8 encoded text file and return its contents. 23 | """ 24 | with codecs.open(filename, 'r', 'utf8') as f: 25 | return f.read() 26 | 27 | setup( 28 | install_requires=[ 29 | "python-daemon", 30 | "schedule", 31 | ], 32 | name='jupyter-cron', 33 | packages=['jupyter-cron'], 34 | version=SCHEDULE_VERSION, 35 | description='Job scheduling based on filenames.', 36 | long_description=read_file('README.rst'), 37 | license='MIT', 38 | author='Quoc Le', 39 | author_email='quocble@gmail.com', 40 | url='https://github.com/quocble/jupyter-cron', 41 | download_url=SCHEDULE_DOWNLOAD_URL, 42 | keywords=[ 43 | 'schedule', 'periodic', 'jobs', 'scheduling', 'clockwork', 44 | 'cron' 45 | ], 46 | classifiers=[ 47 | 'Intended Audience :: Developers', 48 | 'License :: OSI Approved :: MIT License', 49 | 'Programming Language :: Python :: 2.7', 50 | 'Programming Language :: Python :: 3.5', 51 | 'Natural Language :: English', 52 | ], 53 | ) 54 | -------------------------------------------------------------------------------- /jupyter-cron/__main__.py: -------------------------------------------------------------------------------- 1 | import re 2 | import time 3 | import daemon 4 | import glob 5 | import schedule 6 | import pathlib 7 | import os 8 | import argparse 9 | import inspect 10 | from types import FunctionType 11 | import logging 12 | import datetime 13 | 14 | logger = logging.getLogger('jupyter-cron') 15 | ch = logging.StreamHandler() 16 | ch.setLevel(logging.DEBUG) 17 | logger.addHandler(ch) 18 | logging.getLogger().setLevel(logging.DEBUG) 19 | 20 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 21 | ch.setFormatter(formatter) 22 | 23 | parser = argparse.ArgumentParser(description="Scans for file to run on a schedule based on its name") 24 | parser.add_argument("glob", type=str, help="specify glob to search eg. test/**/*.ipynb") 25 | parser.add_argument("-d", "--daemonize", help="daemonize the process", action="store_true") 26 | parser.add_argument("-l", "--log", type=str, help="specify log file") 27 | parser.add_argument("-r", "--refresh", type=int, help="refresh file time (default 5)") 28 | 29 | args = parser.parse_args() 30 | 31 | patternEveryN = re.compile('(.*) \(every (.*) at (.*)\)', re.IGNORECASE) 32 | patternTime = re.compile("(0?[1-9]|1[012])(.[0-5]\d)?[APap][mM]") 33 | 34 | supported_exts = ['.py','.ipynb'] 35 | every_X = ['day', 'monday', 'tuesday', 'wednesday','thursday', 'friday','saturday','sunday'] 36 | 37 | if args.log: 38 | fh = logging.FileHandler(args.log) 39 | fh.setLevel(logging.INFO) 40 | fh.setFormatter(formatter) 41 | logger.addHandler(fh) 42 | logger.info("set log file to " + args.log) 43 | 44 | def job(filename): 45 | # check if file exist, if not remove from schedule 46 | path = pathlib.Path(filename) 47 | 48 | if path.is_file(): 49 | dt_started = datetime.datetime.utcnow() 50 | logger.info ("Running file " + filename + " with ext " + path.suffix) 51 | if path.suffix == '.ipynb': 52 | os.system("jupyter nbconvert --ExecutePreprocessor.timeout=300 --execute \"" + filename + "\"") 53 | if path.suffix == '.py': 54 | os.system("python \"" + filename + "\" > \"" + filename + ".output.txt\"") 55 | 56 | dt_ended = datetime.datetime.utcnow() 57 | seconds = (dt_ended - dt_started).total_seconds() 58 | logger.info ("Job took " + str(seconds) + " seconds") 59 | else: 60 | logger.warn("File does not exist " + filename + ", remove job") 61 | return schedule.CancelJob 62 | 63 | 64 | def build_schedule(): 65 | for filename in glob.iglob(args.glob, recursive=True): 66 | #print (filename) 67 | match = patternEveryN.match(filename) 68 | if match == None: 69 | # logger.info ("format does not match " + filename) 70 | continue 71 | 72 | timeMatch = patternTime.match(match.group(3)) 73 | if timeMatch == None: 74 | logger.info ("time is not correct format " + filename) 75 | continue 76 | 77 | #print (match.group(1,2,3)) 78 | t = None 79 | logger.debug (filename + " matches for schedule") 80 | 81 | if timeMatch.group(2) == None: 82 | t = time.strptime(match.group(3).upper(), "%I%p") 83 | else: 84 | t = time.strptime(match.group(3).upper(), "%I.%M%p") 85 | time_str = f'{t.tm_hour:02d}:{t.tm_min:02d}' 86 | 87 | tagHash = match.group(1) + match.group(2) + match.group(3) 88 | path = pathlib.Path(filename) 89 | 90 | found = [] 91 | found[:] = (job for job in schedule.jobs if tagHash in job.tags) 92 | 93 | # new job - insert / same job will be discarded 94 | if len(found) == 0 and path.suffix in supported_exts: 95 | x = match.group(2).lower() 96 | if x in every_X: 97 | every = schedule.every() 98 | getattr(every, x).at(time_str).do(job, filename).tag(tagHash) 99 | logger.info("inserted new job " + filename) 100 | else: 101 | logger.warn(match.group(2) + " is not valid") 102 | 103 | def setup_schedule(): 104 | refresh = args.refresh and args.refresh or 5 105 | schedule.every(refresh).minutes.do(build_schedule) 106 | build_schedule() 107 | 108 | logger.info ("current schedule") 109 | for j in schedule.jobs: 110 | logger.info (j) 111 | 112 | def run_loop(): 113 | setup_schedule() 114 | 115 | while True: 116 | schedule.run_pending() 117 | time.sleep(1) 118 | 119 | if __name__ == "__main__": 120 | if args.daemonize: 121 | with daemon.DaemonContext(): 122 | run_loop() 123 | else: 124 | run_loop() 125 | --------------------------------------------------------------------------------