use strict; use warnings; use Async::Event::Interval; use Data::Dumper; use IPC::Shareable; use JSON; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $url = 'http://tesla:55556'; # Create a shared scalar string that will hold JSON # data that gets updated by the async event below, which # runs in a separate, unrelated process tie my $fetched_data, 'IPC::Shareable', { key => 'TESLA', create => 1, destroy => 1, }; $fetched_data = ''; # Create an async event that runs in the background. The # 0 parameter means it won't run on an interval, we have to # manually start it each iteration of the loop. We 'start' # it here to send it off on its first run so we have initial # data my $tesla_event = Async::Event::Interval->new(0, \&update_data); $tesla_event->start; my $previous_time = time; my $previous_tesla_data = {charge => -1}; while (1) { # If the background URL fetch is done, start it again. It's probably wise # to time yours to run just prior to your 60 second loop cycle timer # expiring. No sense constantly hitting the site every second if you # don't need the data that quick! $tesla_event->start if $tesla_event->waiting; my $current_time = time; if ($current_time - $previous_time > 3) { my $tesla_data = decode_json($fetched_data); if ($tesla_data->{charge} != $previous_tesla_data->{charge}) { # Do stuff with the result print Dumper $tesla_data; $previous_tesla_data = $tesla_data; } $previous_time = $current_time; } } sub update_data { my $server_response = $ua->get($url); if ($server_response->is_success) { $fetched_data = $server_response->decoded_content; } } #### $VAR1 = { 'fetching' => 0, 'charge' => 0, 'charging' => 0, 'online' => 0, 'error' => 0, 'gear' => 0, 'garage' => 0, 'rainbow' => 0 }; $VAR1 = { 'fetching' => 0, 'charge' => 61, 'charging' => 0, 'online' => 1, 'error' => 0, 'gear' => 0, 'garage' => 1, 'rainbow' => 0 };