title: Setup celery periodic task
body: <p>How do I set up a periodic task with Celerybeat and Flask that queries a database every hour?</p>
  
  <p>The environment looks like this:</p>
  
  <pre><code>/
  |-app
    |-__init__.py
    |-jobs
      |-task.py
  |-celery-beat.sh
  |-celery-worker.sh
  |-manage.py
  </code></pre>
  
  <p>I currently have a query function called <code>run_query()</code> located in <code>task.py</code></p>
  
  <p>I want the scheduler to kick in once the application initiates so I have the following lines in my <code>/app/__init__.py</code> folder:</p>
  
  <pre class="lang-py prettyprint-override"><code>celery = Celery()
  
  @celery.on_after_configure.connect
  def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(1, app.jobs.task.run_query())
  </code></pre>
  
  <p>(For simplicity's sake, I've set it up so that <strong>if</strong> it runs, it will run every minute. No such luck yet.)</p>
  
  <p>When I launch the <code>celery-worker.sh</code> it recognizes my function under the <code>[tasks]</code> heading. But the <strong>scheduled</strong> function never runs. I can manually force the function to run by issuing the following at the command prompt:</p>
  
  <pre><code>&gt;&gt; from app.jobs import task
  &gt;&gt; task.run_query.delay()
  </code></pre>
  
  <p><strong>EDIT</strong>: Added celerybeat.sh</p>
  
  <p>As a follow up: If the database is accessed through a flask context, during my asynch function call is it wise to create a new flask context to access the database? Use the existing flask context? Or forget contexts altogether and just initiate a connection to the database? My worry is that if I just initiate a new connection it may interfere with the existing context's connection?</p>