1

i wan to connect to an api and update some data in database every 20 seconds

so since i want to run it every 20 sec it gets a bit tricky with cronjob , i was wondering if i can use queue and jobs for this

i've created a job

php artisan make:job UpdateData 

and put my code in the UpdateData handle , something like

public function handle()
{
    $options = Option::all();
    foreach ($options as $option)
    {
        $data = CURL($option->url );
        $option->data = $data;
        $option->save();
    }
    
}

im new to queue and if i understand correctly , i need to create a queue table , call queue:work and dispatch this job somewhere in my code so the queue handles the job

but in this case , i just need to run this job every 20 seconds ... there is no dispatch basically i need a infinite loop with 20 sec sleep between them running in the background

so my question is , is this even possible ? if so how can i go about dispatching this job every x sec ... from command line ?

hretic
  • 999
  • 9
  • 36
  • 78
  • My first comment is, do you _really_ need to run every 20 seconds? Cron runs at the minute interval, so if you can live with that, the rest is easy. But if you really need to, I think I'd use a shell script that invokes your code and then sleeps for 20 seconds (or 20 seconds minus how long it takes to run on average), and then use something like supervisord to guarantee that that script is always running. As much as I like queues, I don't think they'd be a good fit for your specific scenario. – Chris Haas Aug 26 '20 at 22:10

2 Answers2

2

Supervisor is a good solution to keep your script alive, or you have 3 choice:

  1. Program that always keep your apps running apt install supervisor
  • Configure the supervisor at /etc/supervisor/conf.d/new-file.conf
[program:your-program]
process_name=%(program_name)s
command=command that you need... exemple php artisan queue:work redis
autostart=true
autorestart=true
user=secure-user
redirect_stderr=true
stdout_logfile=/var/log/script-name.log
stopwaitsecs=3600
  1. Task Scheduling in Laravel that is very easy and i think you can run at specific time and in second: Laravel Scheduling Script

  2. Crontab You will have some choice on them post: Cron 30 seconds Or script bash.

Jud3v
  • 191
  • 3
  • 14
0

so i ended up using a command ,

basically i've create a laravel command put while(true) loop in the command php file , and called the command in terminal

hretic
  • 999
  • 9
  • 36
  • 78