{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# Stack Overflow solution\n", "\n", "* Question: [How do I create a GOOGLE API script to pull data by the hour?](https://stackoverflow.com/q/58615543/1913726)\n", "* Possible solution: [My solution](https://stackoverflow.com/a/58616446/1913726)\n", "\n", "## First accepted answer on Stack Overflow\n", "\n", "![](/images/stackoverflow_screenshots/so_python_scheduler_58615543_1913726.png)"]}, {"cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["Tue Oct 29 22:35:00 2019\n", "Tue Oct 29 22:36:00 2019\n", "Stopped.\n"]}], "source": ["import sched\n", "import time\n", "from datetime import datetime, timedelta\n", "\n", "# Create a scheduler instance.\n", "scheduler = sched.scheduler(timefunc=time.time)\n", "\n", "def reschedule(interval: dict=None):\n", " \"\"\"Define how often the action function will run.\n", " Pass a dict interval {'hours': 1} to make it run every hour.\n", " \"\"\"\n", " interval = {'minutes': 1} if interval is None else interval\n", " # Get the current time and remove the seconds and microseconds.\n", " now = datetime.now().replace(second=0, microsecond=0)\n", " # Add the time interval to now\n", " target = now + timedelta(**interval)\n", " # Schedule the task\n", " scheduler.enterabs(target.timestamp(), priority=0, action=get_report)\n", "\n", "def get_report(analytics=None):\n", " # replace the print call with the code execute the Google API call\n", " print(time.ctime())\n", " \n", " reschedule() # Reschedule so it runs again.\n", "\n", "if __name__ == \"__main__\":\n", " reschedule() # start\n", "\n", " try:\n", " scheduler.run(blocking=True)\n", " except KeyboardInterrupt:\n", " print('Stopped.')"]}], "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.2"}, "nikola": {"category": "Stack Overflow Solutions", "date": "2019-10-30 14:59:49 UTC", "description": "Use Python sched module to run code at intervals.", "link": "", "slug": "run-a-python-script-on-a-schedule-using-the-sched-module", "tags": "code, python, stackoverflow", "title": "Run a Python Script on a Schedule Using the sched Module.", "type": "text"}}, "nbformat": 4, "nbformat_minor": 2}