利用LWP::UserAgent與網頁互動[perl]
用perl去抓twitter的api把其中的資料存到主機上的檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #!/usr/bin/perl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use LWP::UserAgent; use HTTP::Headers; use JSON; our %SITE = ( ); &get_twitter_api(\ %SITE ); sub get_twitter_api { my $site = shift ; my $url ; my $class ; my $agent_name = 'myagent' ; my $ua =LWP::UserAgent->new( $agent_name ); foreach my $k ( keys % $site ) { $url = $site ->{ $k }; $class = $k ; my $request =HTTP::Request->new(GET=> $url ); $request ->header( Accept => 'text/html' ); my $response = $ua ->request( $request ); my $decoded ; my $content = $response ->{_content}; $decoded = &JSON::decode_json( $content ); my $path = '>/XXX/files/' . $class . '/cron/twitter_followers_count.txt' ; open (MYFILE, $path ) || die "Can't open file $path : $!\n" ;; print MYFILE $decoded ->{followers_count}; close (MYFILE); } } |
http://stackoverflow.com/questions/8655487/how-to-convert-string-to-json-in-perl
How to convert string to json in perl
用UA抓回來的資料是字串
要把他轉為json
上文範例中的 use Try::Tiny; 是需要安裝的perl套件
安裝方法: $cpan Try::Tiny
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
15 Awesome Cron Job Examples
跑cron job
1. 查crontab有沒有在跑
$ service crond status
crond (pid 13616) is running...
$ crontab -e 進入編輯
寫入
00 * * * * /usr/bin/perl /home/xxx/cronjob/twitter_followers_count.pl
分 時 日 月 星期
(可先用 * * * * * 每分鐘跑 去看他有沒有跑 或者網路上有用到秒數的方法sleep)
ls -l 看那個檔案最後更新的時間
測試
$ ./your_cron_job.pl
對reference跑迴圈:
http://stackoverflow.com/questions/5249362/how-to-use-foreach-on-hash-a-reference
1 2 3 | foreach my $key ( keys %{ $ad_grp_ref }) { ... } |
Crontab "*/1" 是什麼意思?
http://www.unix.com/linux/136805-crontab-1-a.html
*/1 * * * * /usr/local/bin/jdumpscan.sh
/1是多餘的,等同於每分鐘。等於
* * * * * /usr/local/bin/jdumpscan.sh
設定crontab -e 預設編輯器
http://superuser.com/questions/281617/change-default-text-editor-for-crontab-to-vim
如果預設編輯器不是vim,則使用下面指令設定
export VISUAL=vim
或
export EDITOR=vim
每30秒跑一次cronjob
http://stackoverflow.com/questions/9619362/running-a-cron-every-30-seconds
crontab -e:
* * * * * /usr/bin/bash /home/ds/test.sh
* * * * * ( sleep 30 ; /usr/bin/bash /home/ds/test.sh)
沒有留言:
張貼留言