Execute all mail jobs
169515
public function executeAllAction()
    {
        $this->_helper->BatchRunner(
                $this->loader->getMailLoader()->getCronBatch('commjob-execute-all'),
                $this->_(''),
                $this->accesslog
                );
    }
962269
def run_job(self, job_id, array_id = None):
    """"""
    # set the job's status in the database
    try:
      # get the job from the database
      self.lock()
      jobs = self.get_jobs((job_id,))
      if not len(jobs):
        # it seems that the job has been deleted in the meanwhile
        return
      job = jobs[0]

      # get the machine name we are executing on; this might only work at idiap
      machine_name = socket.gethostname()

      # set the 'executing' status to the job
      job.execute(array_id, machine_name)

      self.session.commit()
    except Exception as e:
      logger.error("Caught exception '%s'", e)
      pass
    finally:
      self.unlock()

    # get the command line of the job from the database; does not need write access
    self.lock()
    job = self.get_jobs((job_id,))[0]
    command_line = job.get_command_line()
    exec_dir = job.get_exec_dir()
    self.unlock()

    logger.info("Starting job %d: %s", job_id, " ".join(command_line))

    # execute the command line of the job, and wait until it has finished
    try:
      result = subprocess.call(command_line, cwd=exec_dir)
      logger.info("Job %d finished with result %s", job_id, str(result))
    except Exception as e:
      logger.error("The job with id '%d' could not be executed: %s", job_id, e)
      result = 69 # ASCII: 'E'

    # set a new status and the results of the job
    try:
      self.lock()
      jobs = self.get_jobs((job_id,))
      if not len(jobs):
        # it seems that the job has been deleted in the meanwhile
        logger.error("The job with id '%d' could not be found in the database!", job_id)
        self.unlock()
        return

      job = jobs[0]
      job.finish(result, array_id)

      self.session.commit()

      # This might not be working properly, so use with care!
      if job.stop_on_failure and job.status == 'failure':
        # the job has failed
        # stop this and all dependent jobs from execution
        dependent_jobs = job.get_jobs_waiting_for_us()
        dependent_job_ids = set([dep.unique for dep in dependent_jobs] + [job.unique])
        while len(dependent_jobs):
          dep = dependent_jobs.pop(0)
          new = dep.get_jobs_waiting_for_us()
          dependent_jobs += new
          dependent_job_ids.update([dep.unique for dep in new])

        self.unlock()
        deps = sorted(list(dependent_job_ids))
        self.stop_jobs(deps)
        logger.warn ("Stopped dependent jobs '%s' since this job failed.", str(deps))

    except Exception as e:
      logger.error("Caught exception '%s'", e)
      pass
    finally:
      if hasattr(self, 'session'):
        self.unlock()
310652
public static function runAll()
    {
        self::checkSapiEnv();
        self::init();
        self::parseCommand();
        self::daemonize();
        self::initWorkers();
        self::installSignal();
        self::saveMasterPid();
        self::forkWorkers();
        self::displayUI();
        self::resetStd();
        self::monitorWorkers();
    }
1119895
def _execute(self, workdir, with_mpirun=False, exec_args=None):
        
        qadapter = self.manager.qadapter
        if not with_mpirun: qadapter.name = None
        if self.verbose:
            print("Working in:", workdir)

        script = qadapter.get_script_str(
            job_name=self.name,
            launch_dir=workdir,
            executable=self.executable,
            qout_path="qout_file.path",
            qerr_path="qerr_file.path",
            stdin=self.stdin_fname,
            stdout=self.stdout_fname,
            stderr=self.stderr_fname,
            exec_args=exec_args
        )

        # Write the script.
        script_file = os.path.join(workdir, "run" + self.name + ".sh")
        with open(script_file, "w") as fh:
            fh.write(script)
            os.chmod(script_file, 0o740)

        qjob, process = qadapter.submit_to_queue(script_file)
        self.stdout_data, self.stderr_data = process.communicate()
        self.returncode = process.returncode
        #raise self.Error("%s returned %s\n cmd_str: %s" % (self, self.returncode, self.cmd_str))

        return self.returncode
188560
def process_import_job(list, emails, report_email = nil, postback_url = nil, options = {})
      data = options
      data['list'] = list
      data['emails'] = Array(emails).join(',')
      process_job(:import, data, report_email, postback_url)
    end
182499
def run(command, options, args):
    """"""

    if command == "backend":
        subprocess.call(("sqlite3", db_path))

    if command == "add":
        dp = pdt.Calendar()
        due = mktime(dp.parse(options.due)[0]) if options.due else None
        print "added tasks..."
        [Task(desc, due).add() for desc in args]
        return

    filters = args if len(args) else None
    rows    = Query(filters, options).find()
    tasks   = [Task(r["desc"], r["due"]) for r in rows]

    if command == "list":
        for t in tasks:
            print "\t *", t

    if command == "done":
        print "done with..."
        finished_tasks = []
        for t in tasks: 
            finished = t.done()
            if finished:
                finished_tasks.append(t)

        if not finished_tasks:
            return

        print ""
        print "finished tasks:"
        for t in finished_tasks:
            print "\t X", t
    
    if command == "remove":
        print "remove..."
        removed_tasks = []
        for t in tasks: 
            removed = t.remove()
            if removed:
                removed_tasks.append(t)
    
        if not removed_tasks:
            return
    
        print ""
        print "removed tasks:"
        for t in removed_tasks:
            print "\t RM", t
1170210
function run(params, command, callback)
{
  var job;

  // decouple commands
  command = clone(command);

  // start command execution and get job reference
  job = executioner(command, stringify(extend(this, params)), this.options || {}, callback);

  // make ready to call task termination function
  return partial(executioner.terminate, job);
}
314068
def clean_old_jobs():
    '''
    
    '''
    if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
        try:
            with _get_serv() as cur:
                sql = 'select date_sub(now(), interval {0} hour) as stamp;'.format(__opts__['keep_jobs'])
                cur.execute(sql)
                rows = cur.fetchall()
                stamp = rows[0][0]

            if __opts__.get('archive_jobs', False):
                _archive_jobs(stamp)
            else:
                _purge_jobs(stamp)
        except MySQLdb.Error as e:
            log.error('Mysql returner was unable to get timestamp for purge/archive of jobs')
            log.error(six.text_type(e))
            raise salt.exceptions.SaltRunnerError(six.text_type(e))
291862
public function run()
	{
		$arcavias = $this->_getArcavias();
		$context = $this->_getContext();
		$config = $context->getConfig();
		$mailer = $context->getMail();
		$view = $context->getView();

		$templatePaths = $arcavias->getCustomPaths( 'client/html' );

		$helper = new MW_View_Helper_Config_Default( $view, $config );
		$view->addHelper( 'config', $helper );

		$client = Client_Html_Email_Payment_Factory::createClient( $context, $templatePaths );

		$orderManager = MShop_Order_Manager_Factory::createManager( $context );
		$orderStatusManager = $orderManager->getSubManager( 'status' );
		$orderBaseManager = $orderManager->getSubManager( 'base' );

		/** controller/jobs/order/email/payment/default/limit-days
		 * Only send payment e-mails of orders that were created in the past within the configured number of days
		 *
		 * The payment e-mails are normally send immediately after the payment
		 * status has changed. This option prevents e-mails for old order from
		 * being send in case anything went wrong or an update failed to avoid
		 * confusion of customers.
		 *
		 * @param integer Number of days
		 * @since 2014.03
		 * @category User
		 * @category Developer
		 * @see controller/jobs/order/email/delivery/default/limit-days
		 * @see controller/jobs/service/delivery/process/limit-days
		 */
		$limit = $config->get( 'controller/jobs/order/email/payment/default/limit-days', 30 );
		$limitDate = date( 'Y-m-d H:i:s', time() - $limit * 86400 );

		$default = array(
			MShop_Order_Item_Abstract::PAY_REFUND,
			MShop_Order_Item_Abstract::PAY_PENDING,
			MShop_Order_Item_Abstract::PAY_AUTHORIZED,
			MShop_Order_Item_Abstract::PAY_RECEIVED,
		);

		/** controller/jobs/order/email/payment/default/status
		 * Only send order payment notification e-mails for these payment status values
		 *
		 * Notification e-mail about payment status changes can be sent for these
		 * status values:
		 * * 0: deleted
		 * * 1: canceled
		 * * 2: refused
		 * * 3: refund
		 * * 4: pending
		 * * 5: authorized
		 * * 6: received
		 *
		 * User-defined status values are possible but should be in the private
		 * block of values between 30000 and 32767.
		 *
		 * @param integer Payment status constant
		 * @since 2014.03
		 * @category User
		 * @category Developer
		 * @see controller/jobs/order/email/delivery/default/status
		 * @see controller/jobs/order/email/payment/default/limit-days
		 */
		foreach( (array) $config->get( 'controller/jobs/order/email/payment/default/status', $default ) as $status )
		{
			$orderSearch = $orderManager->createSearch();

			$param = array( MShop_Order_Item_Status_Abstract::EMAIL_PAYMENT, $status );
			$orderFunc = $orderSearch->createFunction( 'order.containsStatus', $param );

			$expr = array(
				$orderSearch->compare( '>=', 'order.mtime', $limitDate ),
				$orderSearch->compare( '==', 'order.statuspayment', $status ),
				$orderSearch->compare( '==', $orderFunc, 0 ),
			);
			$orderSearch->setConditions( $orderSearch->combine( '&&', $expr ) );

			$start = 0;

			do
			{
				$items = $orderManager->searchItems( $orderSearch );

				foreach( $items as $id => $item )
				{
					try
					{
						$orderBaseItem = $orderBaseManager->load( $item->getBaseId() );
						$view->extOrderBaseItem = $orderBaseItem;
						$view->extOrderItem = $item;

						$addr = $orderBaseItem->getAddress( MShop_Order_Item_Base_Address_Abstract::TYPE_PAYMENT );

						$helper = new MW_View_Helper_Translate_Default( $view, $context->getI18n( $addr->getLanguageId() ) );
						$view->addHelper( 'translate', $helper );

						$message = $mailer->createMessage();
						$helper = new MW_View_Helper_Mail_Default( $view, $message );
						$view->addHelper( 'mail', $helper );

						$client->setView( $view );
						$client->getHeader();
						$client->getBody();

						$mailer->send( $message );

						$statusItem = $orderStatusManager->createItem();
						$statusItem->setParentId( $id );
						$statusItem->setType( MShop_Order_Item_Status_Abstract::EMAIL_PAYMENT );
						$statusItem->setValue( $status );

						$orderStatusManager->saveItem( $statusItem );
					}
					catch( Exception $e )
					{
						$str = 'Error while trying to send payment e-mail for order ID "%1$s" and status "%2$s": %3$s';
						$msg = sprintf( $str, $item->getId(), $item->getPaymentStatus(), $e->getMessage() );
						$context->getLogger()->log( $msg );
					}
				}

				$count = count( $items );
				$start += $count;
				$orderSearch->setSlice( $start );
			}
			while( $count >= $orderSearch->getSliceSize() );
		}
	}
302172
public function execute()
    {
        $mailId = $this->_request->getParam('id');
        $this->_mail = $this->_objectManager->get('\Shockwavemk\Mail\Base\Model\Mail');
        $this->_mail->load($mailId);

        $this->_view->loadLayout();
        $this->_view->getPage()->getConfig()->getTitle()->prepend(__($this->_mail->getSubject()));
        $this->_view->renderLayout();
    }
650353
public function execute()
    {
        $this->contact->resetAllContacts();

        $this->messageManager->addSuccessMessage(__('Done.'));

        $redirectUrl = $this->getUrl('adminhtml/system_config/edit', ['section' => 'connector_developer_settings']);

        $this->_redirect($redirectUrl);
    }
785636
function execute(req, res) {
  var t = systime();
  res.send(null, [t.s, t.m]);
}
1291167
def run(self, **kwargs):
        
        try:
            # connect to server and login
            box = imaplib.IMAP4_SSL(settings.IMAP_SERVER)
            box.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD)
            box.select()

            # search for all mails in the mailbox
            result, mail_indices = box.search(None, 'ALL')

            # if everything was ok...
            if result == 'OK':

                # check number of mails
                mail_count = len(mail_indices[0].split())
                logger.info('found %(mail_count)d mails...' % {'mail_count': mail_count})

                # iterate the mail indices and fetch the mails
                ips_created = 0
                for mail_index in mail_indices[0].split():
                    logger.info('fetching mail %(mail_index)s...' % {'mail_index': int(mail_index)})
                    # mail data is a list with a tuple
                    sub_result, mail_data = box.fetch(mail_index, '(BODY[TEXT])')
                    if sub_result == 'OK':

                        # fetch the ips
                        ips = list_remove_duplicates(
                            self.find_ips(''.join([str(data) for data in mail_data[0]]))
                        )

                        # if ips found, add them and delete the mail
                        if len(ips) > 0:
                            logger.info('found %(count)d IPs' % {'count': len(ips)})
                            ips_created += IP.batch_add_ips(ips)
                            box.store(mail_index, '+FLAGS', '\\Deleted')

                    else:
                        logger.error('fetching mail with index %(index)d failed' % {'index': mail_index})

                # finally, if ips were added, unify the IPs
                if ips_created > 0:
                    logger.info('created %(count)d IPs' % {'count': ips_created})
                    IP.unify_ips()

            else:
                logger.error('search returned not OK')

            box.close()
            box.logout()
        except:
            logger.exception('retrieving mail failed')
1091622
function execute(req, res) {
  // store returns a number but we need to send
  // a bulk string reply
  var reply = req.exec.proxy(req, res);
  res.send(null, '' + reply);
}
460746
function execute(req, res) {
  // TODO: ensure a conflict is triggered on all watched keys
  this.store.flushall();
  res.send(null, Constants.OK);
}
68118
function executeJob (options, opType, callback) {
  var job = client.query(options.namespace, options.set, options.statement)
  var stream = job.execute()
  stream.on('data', function (record) {
    // count the records returned
    intervalData[opType][TPS]++
  })
  stream.on('error', function (error) {
    intervalData[opType][ERROR]++
    if (error.code === status.ERR_TIMEOUT) {
      intervalData[opType][TIMEOUT]++
    }
  })
  stream.on('end', function () {
    // update a stat for number of jobs completed.
    callback(options)
  })
}
1246950
def main():
    

    logging.captureWarnings(True)
    logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' +
                                '%(message)s'), level=logging.INFO)

    print("=====================================")
    print("========   Submit and Wait   ========")
    print("=====================================")
    print("")

    functionJobs = make_jobs()

    print("sending function jobs to cluster")
    print("")

    job_outputs = process_jobs(functionJobs, max_processes=4)

    print("results from each job")
    for (i, result) in enumerate(job_outputs):
        print("Job {0}- result: {1}".format(i, result))