How can I tell Perl to run some code every 20 seconds?

后端 未结 8 802
余生分开走
余生分开走 2021-02-13 15:45

How can I tell Perl to run some code every 20 seconds?

8条回答
  •  孤城傲影
    2021-02-13 16:22

    #!/usr/bin/perl -w
    
    use strict;
    
    
    # heartbeat
    $SIG{ALRM} = sub {
        # set up the next signal for 20 second from now
        alarm(20);
        printf "\n";
    };
    
    alarm(20); # start timer
    my $i = 0;
    while(1) {
        $i++;
        printf "loop" . $i . "\n";
        sleep 2;
    }
    
    alarm(0);
    
    printf "done!\n";
    

    Output :

    loop1
    loop2
    loop3
    loop4
    loop5
    loop6
    loop7
    loop8
    loop9
    loop10
    
    loop11
    loop12
    loop13
    loop14
    loop15
    loop16
    loop17
    loop18
    loop19
    loop20
    
    

提交回复
热议问题