blib/lib/MYDan/Util/FileUpdate.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 70 CC 6 SCAR 17.7
CC
6
Cov
0%
uaget
12.0
new
6.0
run
6.0
CRAP 5.9
1 package MYDan::Util::FileUpdate;
2  
3 =head1 NAME
4  
5 MYDan::Util::FileUpdate
6  
7 =head1 SYNOPSIS
8  
9 use MYDan::Util::FileUpdate;
10  
11 MYDan::Util::FileUpdate->new( output => '/path/file', interval => 3600, url => 'https://xxx' )->run();
12  
13 =cut
14  
15 use strict;
16 use warnings;
17  
18 use Carp;
19 use LWP::UserAgent;
20 use File::Temp;
21  
22 sub new
23 {
24 my ( $class, %self ) = @_;
25 map{ die "$_ undef" unless $self{$_} }qw( url output );
26 bless \%self, ref $class || $class;
27 }
28  
29 sub run
30 {
31 my $this = shift;
32  
33 $this->update();
34  
35 return unless my $interval = $this->{interval};
36  
37 sleep int 3 + rand $interval;
38  
39 while(1)
40 {
41 $this->update();
42 sleep $interval;
43 }
44  
45 return 0;
46 }
47  
48 sub update
49 {
50 my $this = shift;
51  
52 print "update ...\n";
53  
54 my ( $url, $output ) = @$this{qw( url output )};
55 return unless my $c = uaget( $url );
56  
57 my $TEMP = File::Temp->new();
58 print $TEMP $c;
59 system "mv '$TEMP->filename' '$output'";
60 }
61  
62 sub uaget
63 {
64 my $url = shift;
65  
66 my $ua = LWP::UserAgent->new();
67 $ua->agent('Mozilla/9 [en] (Centos; Linux)');
68 $ua->timeout( 10 );
69  
70 my $res = $ua->get( $url );
71 my $code = $res->code();
72 warn "get $url code: $code\n" unless $code == 200;
73 return $res->is_success ? $res->content : undef;
74 }
75  
76 1;