A wrapper around exec

  This exists outside the Scheduler class because it is pickled after it is
  sent to the executor.

def _execute(task):
  """A wrapper around exec

  This exists outside the Scheduler class because it is pickled after it is
  sent to the executor.
  """
  print "[%s] -- %s -- START" % (datetime.datetime.now(), task['id'])
  try:
    with get_app().app_context():
      exec task['code'] in {}, {}
      print "[%s] -- %s -- COMPLETE" % (datetime.datetime.now(), task['id'])
  except Exception as e:
    if isinstance(e, PyCodeError):
      err_msg = "%s: %s\n%s" % (e.data['name'], e.data['message'],
                                ''.join(e.data['traceback']))
    else:
      err_msg = traceback.format_exc()
    sys.stderr.write(err_msg)
    sys.stderr.write("[%s] -- %s -- FAIL\n" % (datetime.datetime.now(),
                                               task['id']))
    email_msg = 'Task %s failed at %s\n\n%s' % (task['id'],
                                                datetime.datetime.now(),
                                                err_msg)
    send_mail(get_app().config['SCHEDULER_FAILURE_EMAILS'],
              'Scheduler Failure', email_msg)
  finally:
    return task