Ejecutar un cron cada 30 segundos


Ok así que tengo un cron que necesito ejecutar cada 30 segundos...esto es lo que tengo a continuación

*/30 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'''

Se ejecuta pero es esto 30 minutos o 30 segundos...y también he estado leyendo que cron podría no ser la mejor herramienta para usar si lo corro tan a menudo. ¿Hay otra mejor herramienta que puedo instalar en ubuntu 11.04 que será una mejor opción o hay una manera de arreglar el anterior cron

Author: Matt Elhotiby, 2012-03-08

14 answers

Tienes */30 en el especificador minutos - eso significa cada minuto pero con un paso de 30 (en otras palabras, cada media hora). Dado que cron no se reduce a resoluciones de menos de un minuto, tendrá que encontrar otra manera.

Una posibilidad, aunque es un poco complicada, es tener dos trabajos, uno compensado por 30 segundos:

* * * * * /path/to/executable param1 param2
* * * * * ( sleep 30 ; /path/to/executable param1 param2 )

Ambos trabajos cron en realidad se ejecutan cada minuto, pero el último esperará medio minuto antes de ejecutar la "carne" del trabajo, /path/to/executable.

 525
Author: paxdiablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-22 02:16:54

No puedes. Cron tiene una granularidad de 60 segundos.

* * * * * cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''
* * * * * sleep 30 && cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''
 51
Author: wildplasser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-08 14:46:36

La granularidad de Cron es en minutos y no fue diseñado para despertar cada x segundos para ejecutar algo. Ejecute su tarea repetida dentro de un bucle y debería hacer lo que necesita:

#!/bin/env bash
while [ true ]; do
 sleep 30
 # do what you need to here
done
 36
Author: Marvin Pinto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-16 17:09:55

No hay necesidad de dos entradas cron, se puede poner en una con:

* * * * * /bin/bash -l -c "/path/to/executable; sleep 30 ; /path/to/executable"

Así que en su caso:

* * * * * /bin/bash -l -c "cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'' ; sleep 30 ; cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''"

 21
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-23 05:23:18

Puedes ver mi respuesta a esta pregunta similar

Básicamente, he incluido allí un script bash llamado "runEvery.sh" que puede ejecutar con cron cada 1 minuto y pasar como argumentos el comando real que desea ejecutar y la frecuencia en segundos en la que desea ejecutarlo.

Algo como esto

*/1 * * * * ~/bin/runEvery.sh 5 myScript.sh

 10
Author: shlomia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

El trabajo Cron no se puede usar para programar un trabajo en un intervalo de segundos. es decir, no puede programar un trabajo cron para ejecutarse cada 5 segundos. La alternativa es escribir un script de shell que use el comando sleep 5 en él.

Crear un script de shell every-5-seconds.sh usando el bucle bash while como se muestra a continuación.

$ cat every-5-seconds.sh
#!/bin/bash
while true
do
 /home/ramesh/backup.sh
 sleep 5
done

Ahora, ejecute este script de shell en segundo plano usando nohup como se muestra a continuación. Esto seguirá ejecutando el script incluso después de salir de la sesión. Esto ejecutará su backup.sh script de shell cada 5 segundos.

$ nohup ./every-5-seconds.sh &
 8
Author: Pankaj Shinde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-15 06:33:51

Use watch:

$ watch --interval .30 script_to_run_every_30_sec.sh
 6
Author: user7079817,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 10:56:29

In dir /etc/cron.d/

Nuevo crea un archivo excute_per_30s

* * * * * yourusername  /bin/date >> /home/yourusername/temp/date.txt
* * * * * yourusername sleep 30; /bin/date >> /home/yourusername/temp/date.txt

Se ejecutará cron cada 30 segundos

 6
Author: LingYFH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-08 01:56:47

Use fcron ( http://fcron.free.fr / ) - le da granularidad en segundos y mucho mejor y más rica en características que cron (vixie-cron) y estable también. Solía hacer cosas estúpidas como tener alrededor de 60 scripts php ejecutándose en una máquina en configuraciones muy estúpidas y aún así hizo su trabajo!

 4
Author: Adi Chiru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-06 23:24:48

El trabajo Crontab se puede usar para programar un trabajo en minutos/horas/días, pero no en segundos. La alternativa :

Crear un script para ejecutar cada 30 segundos:

#!/bin/bash
# 30sec.sh

for COUNT in `seq 29` ; do
  cp /application/tmp/* /home/test
  sleep 30
done

Use crontab -e y un crontab para ejecutar este script:

* * * * * /home/test/30sec.sh > /dev/null
 4
Author: szaier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 12:01:12

Gracias por todas las buenas respuestas. Para hacerlo simple me gustó la solución mixta, con el control en crontab y la división de tiempo en el script. Así que esto es lo que hice para ejecutar un script cada 20 segundos (tres veces por minuto). Línea Crontab:

 * * * * 1-6 ./a/b/checkAgendaScript >> /home/a/b/cronlogs/checkAgenda.log

Script:

cd /home/a/b/checkAgenda

java -jar checkAgenda.jar
sleep 20
java -jar checkAgenda.jar 
sleep 20
java -jar checkAgenda.jar 
 1
Author: jfajunior,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 09:21:26

Acabo de tener una tarea similar que hacer y utilizar el siguiente enfoque :

nohup watch -n30 "kill -3 NODE_PID" &

Necesitaba tener un kill -3 periódico (para obtener el seguimiento de la pila de un programa) cada 30 segundos durante varias horas.

nohup ... & 

Esto está aquí para estar seguro de que no pierdo la ejecución de watch si pierdo el shell (problema de red, bloqueo de Windows, etc.)...)

 0
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 12:13:20

Escribir un script de shell crear archivo. sh

Nano every30second.sh

Y escribir script

#!/bin/bash
For  (( i=1; i <= 2; i++ ))
do
    write Command here
    sleep 30
done

Luego establezca cron para este script crontab-e

(* * * * * /home/username/every30second.sh)

Este cron llama al archivo .sh cada 1 min y en el comando .sh file se ejecuta 2 veces en 1 min

Si desea ejecutar el script durante 5 segundos, reemplace 30 por 5 y cambie el bucle for de la siguiente manera: For (( i=1; i <= 12; i++ ))

Cuando seleccione para cualquier segundo, calcule 60 / su segundo y escriba para bucle

 0
Author: Aditya Gosavi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 16:40:25

Ejecutar en un bucle de shell, ejemplo:

#!/bin/sh    
counter=1
while true ; do
 echo $counter
 counter=$((counter+1))
 if [[ "$counter" -eq 60 ]]; then
  counter=0
 fi
 wget -q http://localhost/tool/heartbeat/ -O - > /dev/null 2>&1 &
 sleep 1
done
 -1
Author: Lo Vega,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 01:34:05