How would I use a cron job to send an HTML GET req

2019-02-26 02:26发布

I would like to set up a cron job which sends an http request to a url. How would I do this? I have never set up a cronjob before.

标签: http shell cron
4条回答
Viruses.
2楼-- · 2019-02-26 02:48

Why can't you use wget. Here is another tutorial.

查看更多
等我变得足够好
3楼-- · 2019-02-26 02:57

A cron job is just a task that get's executed in the background at regular pre-set intervals.

You can pretty much write the actual code for the job in any language - it could even be a simple php script or a bash script.

PHP Example:

#!/usr/bin/php -q
<?php 

file_put_contents('output.txt', file_get_contents('http://google.com'));

Next, schedule the cron job:

10 * * * * /usr/bin/php /path/to/my/php/file > /dev/null 2>&1  

... the above script will run every 10 minutes in the background.

Here's a good crontab tutorial: http://net.tutsplus.com/tutorials/other/scheduling-tasks-with-cron-jobs/

You can also use cURL to do this depending on what request method you want to use:

$url = 'http://www.example.com/submit.php';
// The submitted form data, encoded as query-string-style
// name-value pairs
$body = 'monkey=uncle&rhino=aunt';
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$page = curl_exec ($c);
curl_close ($c);
查看更多
做自己的国王
4楼-- · 2019-02-26 02:59

if you use linux

crontab -e

and add curl command

10 15 * * * /usr/bin/curl --silent http://test.com?some=crontab &>/dev/null

every day 10:15 you will send html GET request to http://test.com with param "some" and value "crontab"

查看更多
祖国的老花朵
5楼-- · 2019-02-26 03:07

Most probably you want do do this as a normal (i.e. non-privileged) user, so assuming that you are logged in as non-root user:

$ echo 'curl -s http://example.com/ > /dev/null' > script.sh
$ chmod +x script.sh
$ crontab -e

Add this entry to do the http request once every 5 minutes:

*/5 * * * * /path/to/your/script.sh

Preferably you don't want script.sh to give any output when there is no error, hence the > /dev/null. Otherwise cron will email the output to (most likely root) every 5 minutes.

That should be enough to get you started. At this point it's good if you invest some time to learn a bit about cron. You'll do well bu reading the appropriate man page for cron:

Start with the format for driving the cron jobs:

$ man 5 crontab

Then with the actual daemon:

$ man cron

General advice: make it a habit of reading the man page of any new unix tools that you encounter, instead of immediately copying and pasting command line snippets, spend some time reading what the switches do.

查看更多
登录 后发表回答