title: Using crontab with django
body: <p>I need to create a function for sending newsletters everyday from crontab. I've found two ways of doing this on the internet :</p>
  
  <p>First - file placed in the django project folder:</p>
  
  <pre><code>#! /usr/bin/env python
  import sys
  import os
  
  from django.core.management import setup_environ
  import settings
  setup_environ(settings)
  
  from django.core.mail import send_mail
  from project.newsletter.models import Newsletter, Address
  
  def main(argv=None):
      if argv is None:
          argv = sys.argv
  
      newsletters = Newsletter.objects.filter(sent=False)
      message = 'Your newsletter.'
  
      adr = Address.objects.all()
      for a in adr:
          for n in newsletters:
              send_mail('System report',message, a ,['user@example.com'])
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>I'm not sure if it will work and I'm not sure how to run it. Let's say it's called run.py, so should I call it in cron with <code>0 0 * * * python /path/to/project/run.py
  </code> ?</p>
  
  <p>Second solution - create my send function anywhere (just like a normal django function), and then create a run.py script :</p>
  
  <pre><code>import sys
  import os
  
  os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
  
  module_name = sys.argv[1]
  function_name = ' '.join(sys.argv[2:])
  
  exec('import %s' % module_name)
  exec('%s.%s' % (module_name, function_name))
  </code></pre>
  
  <p>And then in cron call : <code>0 0 * * * python /path/to/project/run.py newsletter.views daily_job()</code></p>
  
  <p>Which method will work, or which is better ?</p>