Debian Codegraph @

cassandane/Cassandane/Util/Wait.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2017 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Util::Wait;
41 use strict;
42 use warnings;
43 use base qw(Exporter);
44 use Time::HiRes qw(sleep gettimeofday tv_interval);
45
46 use lib '.';
47 use Cassandane::Util::Log;
48
49 our @EXPORT = qw(&timed_wait);
50
51 sub timed_wait
52 {
53 my ($condition, %p) = @_;
54 $p{delay} = 0.010 # 10 millisec
55 unless defined $p{delay};
56 $p{maxwait} = 20.0
57 unless defined $p{maxwait};
58 $p{description} = 'unknown condition'
59 unless defined $p{description};
60
61 my $start = [gettimeofday()];
62 my $delayed = 0;
63 while ( ! $condition->() )
64 {
65 die "Timed out waiting for " . $p{description}
66 if (tv_interval($start, [gettimeofday()]) > $p{maxwait});
67 sleep($p{delay});
68 $delayed = 1;
69 $p{delay} *= 1.5; # backoff
70 }
71
72 if ($delayed)
73 {
74 my $t = tv_interval($start, [gettimeofday()]);
75 xlog "Waited $t sec for " . $p{description};
76 return $t;
77 }
78 return 0.0;
79 }
80
81
82 1;