Search code examples
pythonazurecron

Running Python Scripts in Azure


I have a GitHub repository with some .py scripts. What would be the steps to follow to get them running in Azure through a cron scheduler?


Solution

  • My recommendation would be to use Azure Python Functions with a time trigger binding and call your Python modules from there.

    A simplistic sample project structure could look like this

    ├── function-app/
    │   ├── __init__.py
    │   └── function.json
    └── shared/
        └── your_module.py
    

    where __init__.py contains the Azure Function wrapper code that gets executed according to the cron schedule

    from __app__.shared.your_module import your_function
    
    def main(mytimer: func.TimerRequest) -> None:
        utc_timestamp = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
    
        logging.info('Python timer trigger function ran at %s', utc_timestamp)
    
        # call your_function() here
    

    and function.json contains among others the cron schedule expression, in this example running every 6 hours.

    {
      "scriptFile": "__init__.py",
      "bindings": [
        {
          "name": "mytimer",
          "type": "timerTrigger",
          "direction": "in",
          "schedule": "0 0 */6 * * *"
        }
      ]
    }