Git Product home page Git Product logo

jobby's Introduction

Jobby, a PHP cron job manager

Total Downloads Latest Version Build Status MIT License

Install the master jobby cron job, and it will manage all your offline tasks. Add jobs without modifying crontab. Jobby can handle logging, locking, error emails and more.

NEW REPO: We have moved jobby to a Github org. Please update your remotes to https://github.com/jobbyphp/jobby.git.

Features

  • Maintain one master crontab job.
  • Jobs run via PHP, so you can run them under any programmatic conditions.
  • Use ordinary crontab schedule syntax (powered by the excellent cron-expression).
  • Run only one copy of a job at a given time.
  • Send email whenever a job exits with an error status.
  • Run job as another user, if crontab user has sudo privileges.
  • Run only on certain hostnames (handy in webfarms).
  • Theoretical Windows support (but not ever tested)

Getting Started

Installation

The recommended way to install Jobby is through Composer:

$ composer require hellogerard/jobby

Then add the following line to your (or whomever's) crontab:

* * * * * cd /path/to/project && php jobby.php 1>> /dev/null 2>&1

After Jobby installs, you can copy an example file to the project root.

$ cp vendor/hellogerard/jobby/resources/jobby.php .

Running a job

<?php 

// Ensure you have included composer's autoloader  
require_once __DIR__ . '/vendor/autoload.php';

// Create a new instance of Jobby
$jobby = new Jobby\Jobby();

// Every job has a name
$jobby->add('CommandExample', [

    // Run a shell command
    'command'  => 'ls',

    // Ordinary crontab schedule format is supported.
    // This schedule runs every hour.
    'schedule' => '0 * * * *',

]);

$jobby->run();

Examples

Logging

<?php

/* ... */

$jobby->add('LoggingExample', [
    
    'command' => 'ls',
    'schedule' => '0 * * * *',
    
    // Stdout and stderr is sent to the specified file
    'output' => 'logs/command.log',

]);

/* ... */

Disabling a command

<?php

/* ... */

$jobby->add('DisabledExample', [
    
    'command' => 'ls',
    'schedule' => '0 * * * *',
    
    // You can turn off a job by setting 'enabled' to false
    'enabled' => false,

]);

/* ... */

Running closures

When running closures, beware that nothing outside of the closure is visible (see #93)!

<?php

/* ... */

$jobby->add('ClosureCommandExample', [
    
     // Use the 'closure' key
     // instead of 'command'
    'closure' => function() {
        echo "I'm a function!\n";
        return true;
    },
    
    'schedule' => '0 * * * *',

]);

/* ... */

Using a DateTime

<?php

/* ... */

$jobby->add('DateTimeExample', [
    
    'command' => 'ls',
    
    // Use a DateTime string in
    // the format Y-m-d H:i:s
    'schedule' => '2017-05-03 17:15:00',

]);

/* ... */

Using a Custom Scheduler

<?php

/* ... */

$jobby->add('Example', [
    
    'command' => 'ls',
    
    // Use any callable that returns
    // a boolean stating whether
    // to run the job or not
    'schedule' => function(DateTimeImmutable $now) {
        // Run on even minutes
        return $now->format('i') % 2 === 0;
    },

]);

/* ... */

Supported Options

Each job requires these:

Key Type Description
schedule string Crontab schedule format (man -s 5 crontab) or DateTime format (Y-m-d H:i:s) or callable (function(): Bool { /* ... */ })
command string The shell command to run (exclusive-or with closure)
closure Closure The anonymous PHP function to run (exclusive-or with command)

The options listed below can be applied to an individual job or globally through the Jobby constructor. Global options will be used as default values, and individual jobs can override them.

Option Type Default Description
runAs string null Run as this user, if crontab user has sudo privileges
debug boolean false Send jobby internal messages to 'debug.log'
Filtering Options to determine whether the job should run or not
environment string null or getenv('APPLICATION_ENV') Development environment for this job
runOnHost string gethostname() Run jobs only on this hostname
maxRuntime integer null Maximum execution time for this job (in seconds)
enabled boolean true Run this job at scheduled times
haltDir string null A job will not run if this directory contains a file bearing the job's name
Logging Options for logging
output string /dev/null Redirect stdout and stderr to this file
output_stdout string value from output option Redirect stdout to this file
output_stderr string value from output option Redirect stderr to this file
dateFormat string Y-m-d H:i:s Format for dates on jobby log messages
Mailing Options for emailing errors
recipients string null Comma-separated string of email addresses
mailer string sendmail Email method: sendmail or smtp or mail
smtpHost string null SMTP host, if mailer is smtp
smtpPort integer 25 SMTP port, if mailer is smtp
smtpUsername string null SMTP user, if mailer is smtp
smtpPassword string null SMTP password, if mailer is smtp
smtpSecurity string null SMTP security option: ssl or tls, if mailer is smtp
smtpSender string jobby@<hostname> The sender and from addresses used in SMTP notices
smtpSenderName string Jobby The name used in the from field for SMTP messages

Symfony integration

Symfony bundle for Jobby - imper86/jobby-cron-bundle

Credits

Developed before, but since inspired by whenever.

Support this project

jobby's People

Contributors

alexeymorozov avatar alpacagh avatar b3none avatar bentinata avatar bitdeli-chef avatar bukashk0zzz avatar christof-b avatar danielzambranoc avatar darkalchemy avatar exptom avatar fire015 avatar garethellis36 avatar hellogerard avatar imper86 avatar jamesmbowler avatar jbaron-gingco avatar jdurand avatar kasp3r avatar kbariotis avatar kusmierz avatar llwt avatar loginwashere avatar mstraczkowski avatar nyholm avatar qconer avatar schultemarkus avatar simasgodovan avatar stricte avatar swader avatar vahurk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jobby's Issues

If script runed under Jobby is unexpectedly die...

What we can do in this case?
Manually check and remove .loc file is not cool, but Im cant find any checks for realy process running(and automatically remove .lock file if process with pid from lock file is not exist)

Lockfile permissions not set

I've run into a permissions issue when running crons from multiple users due to lockfile ownership. When user_a runs jobby the lockfile is created and owned by user_a. When user_b later goes to run, it can't use the lockfile because it doesn't have write permissions.

IMO the mode should be set to 0666.

Is this intended functionality? If not, I'll gladly send a PR for a chmod in Helper :)

Run specific jobs INSIDE the main process

I'd like to tell jobby to invoke my closure directly inside the main process - when calling $jobby->run() to be clear.
That way I can use the same environment, w/o the need to spawn a new process

Force PHP version

Hello,

Is there a way to override the php version that jobby uses to run cron jobs. I have a script which runs fine on my webserver which uses PHP 5.6 but when I run the same php script in cron it gives errors related to the php version. I run a phpinfo() as a php script in crontab and got php version 5.4.45.

Can jobby be configured to use a different php version?

Thanks

How does Jobby handle overlapping jobs?

Hi,
Suppose I have a mailer that sends emails every minute, for one minute the number of emails in the queue is high and somehow the process will last 65 seconds, now after 60 seconds the job is re-run again, and it might pick some stuff from the queue while they are being processed by the previous job.
Is it programmers duty to handle this with some sort of lock or Jobby can handle that somehow?
This library php-cron-scheduler seems to have some sort of temp folder and checking mechanism for this, which I didn't find in the readme file of Jobby.
Thanks

Jobby locks task

#Jobby locks current task from repeating while executing
it seems that Jobby lock the current task while it's still being executed, so if the task is supposed to run every minute and it's running at the moment, the next time it should be executed just won't happen until the one before. There is any workaround for this?

Windows support

Hi,

you declared there is theoretical Windows support (and I see $this->runWindows($job, $config); in your code) , but you use "posix" php extension:

if (! extension_loaded('posix')) {
throw new Exception("'posix' extension is required");
}

and this extension is not available for Windows.

Cronjob not being added.

Here are my current settings. The "hello." is getting echoed out, so I know the code works and everything. I even did a "is_class()" on it.

screen shot 2014-02-22 at 11 15 25 pm

Oh, and when I ran the default jobby.php file, it crashed my server and all of my processes went into "D" state.

What's up with that? Do I need something on my server configured?

Crontab entry: What should jobby.php be?

Hey guys,
I think that's kind of stupid question but I don't get it:
You say I've to add this line to my crontab:
* * * * * cd /path/to/project && php jobby.php 1>> /dev/null 2>&1
But I just don't know what file php jobby.php should be? I've got src/Jobby.php, okay. And I also have resources/jobby.php (which is just an example file).

Should this file be the file that queries all the cron-jobs from my database and run them manually? Is the creation of jobby.php on my own? Is there an example? Does Jobby store the "added" cron-jobs anywhere? Or ist that also my job?

My destination is to implement a cron-job system that can contain dynamic cron-jobs which will be managed by database, so the user has all this under his own control.

Maybe I'm a bit stupid, but please help me.
Jan

Job silently fails under Win7 + Git BASH

When run under Win7 + Git BASH Jobby fails to load the subprocess with absolutely no output to the user. The actual problem is the way Jobby tries to start the subprocess:

start "blah" /B "c:\xampp\php\php.exe" "run.php"

gives me an error ("can not find blah") under Git BASH, but does work under normal windows cmd.

I would appreciate if you could find a way to warn the user, if the command fails to start!

Chaining Command support ?

Is there any plan to add features for chaining-commands ? I think it might quite useful due to sometime a job might have commands that must execute in sequence.

[Question] Why is shouldRun determined in background job?

It seems like it would be way faster to determine which jobs should be started in main process (maybe aside from locking), then only run those background jobs. Thoughts?

Also: This would also have a huge savings on not serializing closures that don't need to run.

Jobby not executing code with cron job

I am able to run jobby.php from a shell and it works "php jobby.php" but when it's running from a cron job, the code inside doesn't get executed.
I have verified in the logs jobby is being executed in cron every minute. I even added a php file with same format for cron job which sent out an email and it ran and generated the email every minute.

Here is cron job format for jobby:

/usr/local/bin/php /home/mydir/public_html/jobby.php 1>> /dev/null 2>&1
and another
php -q /home/mydir/public_html/jobby.php 1>> /dev/null 2>&1

Here is a cron log entry showing jobby being run:

Apr 4 03:57:01 myserver crond[12094]: (myuser) CMD (/usr/local/bin/php /home/myuserl/public_html/jobby.php 1>> /dev/null 2>&1)

So we have verified that cron is working. Jobby work from the command line but doesn't work when being driven by cron.

Anyone have any suggestions for modifying my configuration or anything else to try to get jobby to run via cron? I'm using Cpanel & CentOS.

Timezone issues

It seems that jobby runs at EST timezone on my machine.

The server is configured to show a different timezone, and I also tried using date_default_timezone_set in the jobby file but the cron expressions are still considered as if they are EST.

Is this by design, or a bug, or have I missed something?

Alternative configuration for windows servers.

How would a alternative configuration on Windows Task Manager for:

* * * * * cd /path/to/project && php jobby.php 1>> /dev/null 2>&1

I'm concerned about the performance of a script running every time.

The output is not being set properly

If I do not set any output file explicitly, when the configuration is sent from Jobby to BackgroundJob, the $config['output'] is set to null. This causes an error in the resulting bash command, because the output is something like:

php whatever.php 1>> 2>&1

However, if no output is set, this should be:

php whatever.php 1>> /dev/null 2>&1

The work around I've found is to explicitly set the output key in the array that I instantiate Jobby with:

$jobby = new \Jobby\Jobby(['debug' => true, 'output' => 'crons.log']);

The way to fix this is also very simple. In Jobby.php, on line 75, there's a default value being set for output:

return array(
    // ...
    'output' => null,
    // ...
);

Simply, change this to /dev/null so that the resulting command would have the correct syntax.

URL Command Support

Is it possible to use wget or curl for url commands like below? If not currently supported, can this be added as a feature request or enhancement?

require_once __DIR__ . '/vendor/autoload.php';

$jobby = new Jobby\Jobby();

// Every job has a name
$jobby->add('CommandExample', [
    // Run a wget/cURL commands
    'command'  => 'wget http://localhost/cron/purgeErrorLog/',

    // Ordinary crontab schedule format is supported.
    // This schedule runs every hour.
    // You could also insert DateTime string in the format of Y-m-d H:i:s.
    'schedule' => '0 * * * *',

    // Stdout and stderr is sent to the specified file
    'output'   => 'logs/command.log',

    // You can turn off a job by setting 'enabled' to false
    'enabled'  => true,
]);

$jobby->run();

Handling of two jobs with the same name

I recently had an issue in a project that creates jobs dynamically. I noticed that some jobs weren't running. It turned out that some jobs shared the same id that was passed as the job parameter to the Jobby->add method. It would be nice if the add method would throw an exception if there already is a job with the same name.

Updating 2.2.0 to 3.x.x

I'm running into the following issue updating to either 3.0.0 or 3.0.1:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: jeremeamia/SuperClosure[2.2.0, 2.1.0].
- Can only install one of: jeremeamia/SuperClosure[2.2.0, 2.1.0].
- Can only install one of: jeremeamia/SuperClosure[2.2.0, 2.1.0].
- hellogerard/jobby v3.0.1 requires jeremeamia/superclosure ^2.2 -> satisfiable by jeremeamia/SuperClosure[2.2.0].
- Installation request for hellogerard/jobby v3.0.1 -> satisfiable by hellogerard/jobby[v3.0.1].
- Installation request for jeremeamia/superclosure == 2.1.0.0 -> satisfiable by jeremeamia/SuperClosure[2.1.0].

[Feature] Support for @reboot

It would be nice to be able to schedule commands for @reboot. I realize this might be an additional line in the crontab, but it would be nice if Jobby could somehow account for it.

split stdout and stderr ?

At current configuration, we only have 1 output option - that stdout and stderr can only be written in same log file. I think it might be better if jobby have feature to split the stdout and stderr in different log file.

`maxRuntime' setting won't work on MS Windows

If maxRuntime is used, then Helper#getLockLifetime may be executed,
even on a Microsoft Windows host. That's a problem, because the method
contains Unix-specific code.

BTW, in case you're not aware: the maxRuntime setting is undocumented.

Not an issue exactly but require help

Hi @hellogerard,

Great job putting up this repo. I am somehow unable to run it.

I am trying to run it on CentOS 6.4 instance running nginx and php-fpm. The script I am trying to execute is owned and belongs to group "nginx" with permission 0755. I've set the crontab of user nginx to run jobby.php every minute.

$jobby->add('ListDir', array( 'command' => 'cd scripts && sudo ls -l', 'schedule' => '* * * * *', 'output' => 'logs/closure.log', 'enabled' => true, 'debug' => true, ));

The only thing that gets printed in debug.log is:: "sh: logs/closure.log: No such file or directory"

and in logs/closure.log is:: "[2013-12-24 10:11:01] ERROR: Job exited with status '1'."

Now this looks like a permission issue somewhere, but since nothing is printed in the logs, how do I debug?

Thanks,
Prasenjit.

Failing to autoload

Using the same code as in the example for CommandExample Jobby is failing to autoload the vendor directory in BackgroundJob.php:

PHP Warning:  require(/home/www/sites/vendor/hellogerard/jobby/vendor/autoload.php): failed to open stream: No such file or directory in /home/www/sites/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php $
PHP Stack trace:
PHP   1. {main}() /home/www/sites/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php:0
PHP Fatal error:  require(): Failed opening required '/home/www/sites/vendor/hellogerard/jobby/vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /home/www/sites/vendor/hellogerard/jo$
PHP Stack trace:
PHP   1. {main}() /home/www/sites/vendor/hellogerard/jobby/src/Jobby/BackgroundJob.php:0

Looks like Jobby is looking for the vendor autoload.php script inside it's own directory which doesn't exist as it should be in the root vendor directory (/home/www/sites/vendor/).

Protected -> Private - Why?

Why were methods changed to private? This only makes Jobby less extendable. I have a couple cases where I've overridden some methods and 2.1 breaks this.

Serialization of closure failed: Serialization of 'Closure' is not allowed

I'm having a strange issue. I'm getting a:
Notice: Serialization of closure failed: Serialization of 'Closure' is not allowed in /path/to/php/file.php error.

This happens only when I use the use statement. So this code is causing the issue:

$app = new App();
$config = $app->config();
$logger = $app->getLogger();

$jobby->add('export-all', [
    'schedule' => $config->get("cron:export-all"),
    'closure'  => function () use ($app, $logger, $config) {
        // Do something
    },
]);

But this is fine:

$jobby->add('export-all', [
    'schedule' => $config->get("cron:export-all"),
    'closure'  => function () {
        $app = new App();
        $config = $app->config();
        $logger = $app->getLogger();
        // Do something
    },
]);

But, this is not a rule! Not always when I use the use statement I'm having this issue. But always when I'm getting this issue getting rid of the use statement solves the problem.


I know that Jobby is using SuperClosure internally, so it probably has something to to with SuperClosure not Jobby itself.

hello,how can i integration with CodeIgniter

    $task['task_sync_order']['closure'] = function (){
       $this->load->model('model_name');
        return true;
    };

while i am doing this ,it do nothing, how can i solve this problem,thanks

[Request] ScheduleChecker->isOverdue

I don't quite understand the concept of limiting jobs to the scheduled minute. If the server somehow skipped a bunch of jobs, there's no option to run them again?

Jobby->run() only uses the ScheduleChecker provided isDue() function to compare the current minute to scheduled tasks. I imagine there are needs for this behaviour, but why not provide another option that checks if the scheduled time is behind the current time?

We have to either delete the jobs ran, or flag them anyways, so it's not like every time Jobby runs it executes all the old jobs again.

I would love to have this built-in rather than having to custom a lot of code outside Jobby to avoid composer update overwrites.

Issues with XDebug & listening for connections

Hi,

I've found that when I run my Jobby-runner while PhpStorm is listening for XDebug debug connections, Jobby blocks indefinitely and PHP can't run at all in any other process (whether php-cgi or CLI). This happens regardless of whether I have set any breakpoints.

This may not be anything that can be solved, but I wanted to raise it hear as an "FYI" - I've just lost three hours to trying to resolve this one :)

Closure definition unclear

I think maybe it should be specified that closures are also executed in a separate process. Ran into problems thinking that the closure was executed by the current php process until I looked at the actual code.

Jobby doesn't follow schedule parameter

I set up Jobby as described and added a corresponding entry to my crontab.

However: The schedule I set gets disregarded and all jobs run everytime Jobby is run.

If I set Jobby in chrontab to run every minute and a job in jobb to run every ten minutes, it runs every minute. If i set Jobby to run only every five minutes, the job runs every five minutes.

Any idea why it doesn't take the schedule parameter into account?

Thanks,
Florian

Fixed vendor directory

Hi there,

first time I'm using composer to use jobby and as I didn't want to create a vendor directory, I added in my composer.json :

"config": {
    "vendor-dir": "php/lib"
},

But when using jobby I got :

PHP Fatal error:  require(): Failed opening required '/.../php/vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /.../php/lib/hellogerard/jobby/src/Jobby/BackgroundJob.php on line 290

so I checked the line 290 :

require(dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '/vendor/autoload.php');

and replace it by :

require(dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '/lib/autoload.php');

to reflect my actual path. It works but there should be a better way of doing this by retrieving composer "vendor" directory set in config file and not hard writing it !

Thanks for the tool anayway !!

How does it deal with missed Jobs

How does it track missed jobs?
For example if cron is scheduled to run at exact 2 AM every night
but jobby misses it because it is running other jobs, will it run 2 AM job?

How it deals with missed jobs in general?

Thanks

Task regularly exceeding maxRuntime, skipping beats

I'm running OS X as the host environment, on which I'm powering Homestead Improved. I installed Jobby into one such environment (namely nofw) as an experiment, but skipping the config file etc, basically directly hitting the jobby file. The jobby file looks something like this in this experimental demo stage:

<?php

use Dotenv\Dotenv;
use Jobby\Jobby;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

require __DIR__ . '/../vendor/autoload.php';

$logger = new Logger('cronlog');
$logger->pushHandler(
    new StreamHandler(__DIR__ . '/../logs/cron-error.log', Logger::ERROR)
);

$d = new Dotenv(__DIR__ . '/../');
$d->load();

try {
    $db = new PDO(
        'mysql:host=' . getenv('MAIN_DB_HOST') . ';dbname=' . getenv(
            'MAIN_DB_NAME'
        ), getenv('MAIN_DB_USER'), getenv('MAIN_DB_PASS')
    );

    $settings = $db->query('SELECT * FROM `cron_settings`')->fetchAll(
        PDO::FETCH_ASSOC
    );
    $crons = $db->query(
        'SELECT * FROM `cron` WHERE `status` = "active"'
    )->fetchAll(
        PDO::FETCH_ASSOC
    );
} catch (PDOException $e) {
    $logger->error('Error while fetching DB contents: ' . $e->getMessage());

    return;
}

$jobby = new Jobby(
//    [
//        'mailer' => 'smtp',
//        'smtpUsername' => getenv('MAILGUN_SMTP_LOGIN'),
//        'smtpPassword' => getenv('MAILGUN_SMTP_PASS'),
//        'smtpHost' => getenv('MAILGUN_SMTP_HOST'),
//    ]
);

$settings = [
    'maxRuntime' => 50,
    'recipients' => '[email protected]',
    'output' => 'cron.log',
];

$crons = [
    [
        'id' => 1,
        'name' => 'Job 1',
        'description' => 'Foo bar',
        'status' => 'enabled',
        'schedule' => '* * * * *',
        'maxRuntime' => 10,
        'output' => 'j1.log',
        'environment' => 'dev',
        'command' => 'dateffds',
    ],
    [
        'id' => 2,
        'name' => 'Job 2',
        'description' => 'Foo baz',
        'status' => 'enabled',
        'schedule' => '/5 * * * *',
        'maxRuntime' => 10,
        'output' => 'j2.log',
        'recipients' => '[email protected]',
        'environment' => 'dev',
        'command' => 'ls',
    ],
];

/** @var array $cron */
foreach ($crons as $cron) {
    $cron = array_merge($settings, array_filter($cron));
    $jobName = $cron['name'];
    unset($cron['name']);
    $cron['output'] = ($cron['output'] ?? false) ? __DIR__ . '/../logs/' . $cron['output'] : __DIR__ . '/../logs/cron.log';
    $jobby->add($jobName, $cron);
}

$jobby->run();

So two fake jobs and a basic "global" settings array. The DB calls above are there just for show, the DB is empty. That entire part can be removed.

Anyway. You'll notice the first job has a bogus command: dateffds. This throws a normal error any time when called on the command line. The jobby file itself does not hang when called directly from the command line, and there's nothing execute, so it's odd to be constantly getting this from job1:

screenshot 2016-03-19 23 22 11

I then looked into lockfiles and explored the Helper class, where I then added some logging calls to each IF block, in order to pinpoint what fails and when. This is what I got, side by side (inside.log are log entries from within Helper, while j1.log is output from job 1):

screenshot 2016-03-20 00 00 34

These are the forced logging messages I added to Helper:

    /**
     * @param string $lockFile
     *
     * @return int
     */
    public function getLockLifetime($lockFile)
    {
        $l = new Logger('foo');
        $l->pushHandler(new StreamHandler(__DIR__.'/../../../../logs/inside.log'));

        if (!file_exists($lockFile)) {
            $l->info("File does not exist");
            return 0;
        }

        $pid = file_get_contents($lockFile);
        if (empty($pid)) {
            $l->info("PID is empty");
            return 0;
        }

        if (!posix_kill(intval($pid), 0)) {
            $l->info("No posix kill");
            return 0;
        }

        $stat = stat($lockFile);

        $l->info("All good");
        return (time() - $stat["mtime"]);
    }

If you have any ideas on what I should test next, please let me know, though you'd probably see it most clearly if you tried it out on Homestead Improved - it's just a basic Ubuntu 14.04 box with PHP 7.

More info:

  • the tmp files are not in a shared folder, it can't be fighting with the host OS for control over lockfiles
  • the tmp files are not visible in my IDE, so they're not being fought over on that front either
  • at first, it worked without these timeouts
  • after a reboot of the VM (once the tmp files are killed off), the situation resumes as soon as the files are recreated. So just one successful call and we're back to the timeouts again.

Extending Helper Class

It would be nice to have the ability to easily extend the helper class.

In my case, I cannot write to the file system. Instead, I would extend Helper's acquireLock(), releaseLock(), & getLockLifetime() functions to make them read / write to a table.

BackgroundJob accepts a third parameter for the helper class, but run-job does not pass anything for that parameter.

My alternative is to extend Jobby to make the property 'script' a different script that would do the same thing as run-job, but pass BackgroundJob a new Helper class. Is this the route you would recommend?

Consider moving to an organization?

This would allow much more flexibility in the future. Maintainers could come and go without changing links. See what fabpot has to say about it here.

Let me know what you think.

Email output (not errors) ?

Hi,

Sorry if I missed something about it but it would be great if we could mail the output, just like normal cronjobs offer. As far as I understand, jobby only mails errors (Exception) but not output?

Regards

Class 'Jobby' not found

PHP Fatal error: Class 'Jobby' not found in /home/mydir/public_html/jobby.php on line 11

I have been getting this error repeatedly. I have reinstalled jobby and followed the instructions line by line.

My root is public_html and my server is cpanel.

Can't get it to run

Hi, I tried your sample script and changed the schedule to * * * * * so it runs every minute. But when I run: php jobby.php in console it does not do anything, no echos, no errors, no output, nothing.

I went into your source and double checked and it finds the job in $jobs at least as it is run.

But why can't I get it to run the job and execute the "ls" command?

I can execute exec() with a test script without any issues.

Is it possible to make one job conditional on success of another?

This is a nice little tool but I was wondering if there was a way to make one job execute only if the another job was successful. For example, run job 1 at 7:00 and then run job 2 at 7:30 but only if job 1 was successful. A similar idea might be to not even specify a time for job 2 but just run it after job 1 but only if job 1 is successful. Currently I am doing this in code but it isn't very elegant.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.