How do I setup a cron job a script that is part of a zend framework project

后端 未结 3 1316
难免孤独
难免孤独 2021-02-20 10:58

I have a zendframework project for which i need to run a script periodically to upload the content of a folder and another do download. The script itself is ready but I am strug

相关标签:
3条回答
  • 2021-02-20 11:13

    Thanks all for your answers. However the solution that worked for me came from this site Howto: Zend Framework Cron. The original link is dead, but its copy can be found on Internet Archive.

    I am posting a cut of the code here. But please this is not my solution. All credits goes to the original author.

    The trick with cronjobs is that you do not want to load the whole View part of ZF, we don't need any kind of HTML output! To get this to work, I defined a new constant in the cronjob.php which I will check for in the index.php.

    cronjob.php

    define("_CRONJOB_",true);
    require('/var/www/vhosts/domain.com/public/index.php');
    // rest of your code goes here, you can use all Zend components now!
    

    index.php

    date_default_timezone_set('Europe/Amsterdam');
    
    // Define path to application directory
    defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
    
    // Define application environment
    defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
    
    // Ensure library/ is on include_path
    set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
    )));
    
    /** Zend_Application */
    require_once 'Zend/Application.php';
    
    // Create application, bootstrap, and run
    $application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
    );
    $application->bootstrap();
    
    /** Cronjobs don't need all the extra's **/
    if(!defined('_CRONJOB_') || _CRONJOB_ == false)
    {
    $application->bootstrap()->run();
    }
    
    0 讨论(0)
  • 2021-02-20 11:24

    First, make sure you have this at the top of your PHP script (followed by the opening PHP tag):

    #!/usr/bin/php
    <?php
        // ...
    

    Second, make sure the permissions are right. For example, if you create the cron job under root, then I believe root will try to run the PHP script if I'm not mistaken. Likewise, if you create the cron job under a different user, they better have the correct permissions to the PHP script.

    For example (note, depending on your server environment, the permissions will need to be adjusted accordingly. e.g. this is just a hypothetical example)

    $ chmod 755 script.php
    $ chown userThatRunsScriptWithCron script.php
    

    If you want to see the current cron jobs for the current user you're logged in as, do this:

    $ crontab -l
    

    Or, if your cron job is set up in one of the folders such as cron.hourly, cron.weekly, etc, then you can view which user "owns" those jobs by doing this:

    $ cat /etc/crontab
    

    Then at the bottom of the file you'll see them.

    Now, to setup the cron job run this command to open the editor:

    $ crontab -e
    

    Then enter your values:

    1 2 3 4 5 php /path/to/script.php
    

    Now save and close the file. Obviously, you're going to change 1 2 3 4 5 to something real and meaningful. For more information about that see this page (google "cron").


    Disclaimer: I am not a cron master by any means. Please correct me on any of this if I'm wrong.

    0 讨论(0)
  • 2021-02-20 11:28

    What I did was create a mini app called Scripts here is the structure:

    Scripts
     -- Jobs
     -- Builds
     Abstract.php //abstract each job / build inherit from
     Bootstrap.php
     Index.php
    

    I then use php /path/to/Scripts/Index.php --j=folderScript or /path/to/Scripts/Index.php --b=folderScript for a build script

    I then overload the main zend_application bootstrap run method like so

    public function run()
    {
        $opts = new Zend_Console_Getopt(array(
                    'build|b-s' => 'Cron Build Script to Run',
                    'job|j-s' => 'Cron Job to run',
                    'params|p-s' => 'Parameters to set',
                ));
    
        $opts->parse();
    
        $front = $this->getResource('FrontController');
    
        if (true === isset($opts->params)) {
            parse_str($opts->params, $params);
            $front->setParams($params);
        }
    
        $filter = new Zend_Filter_Word_CamelCaseToUnderscore();
    
        if (true === isset($opts->build)) {
            $build = $filter->filter($opts->build);
            $className = sprintf('Scripts_Build_%s', ucfirst($build));
        } else if (true === isset($opts->job)) {
            $job = $filter->filter($opts->job);
            $className = sprintf('Scripts_Jobs_%s', ucfirst($job));
        } else {
            $className = 'Scripts_Jobs_Dynamic';
        }
    
        if (false === class_exists($className)) {
            throw new Exception('Class "' . $className . '" Does Not Exist');
        } else {
            $front->setParam('bootstrap', $this);
    
            $logger = $this->initLogger();
    
            $fp = fopen(DATA_PATH . '/locks/' . md5($className), 'w+');
    
            if (!flock($fp, LOCK_EX | LOCK_NB)) {
                $logger->info('Already Running');
                exit(0);
            }
    
            $logger->Subject($className);
    
            fwrite($fp, time());
    
            try {
                $class = new $className();
    
                $class->setLogger($logger)
                        ->init()
                        ->run();
    
                $logger->done('Operation Completed');
            } catch (Exception $e) {
                $logger->err($e->getMessage() . ' ' . $e->getTraceAsString());
                $logger->done('done with error');
            }
    
            flock($fp, LOCK_UN);
        }
    }
    

    Hope that gets you started, I looked at using a controller / module within ZF but seemed like too much overhead

    Symfony uses a good approach with their app/console as well, could be worth looking into their setup

    0 讨论(0)
提交回复
热议问题