Merge branch 'rb-wiederkehrende-rechnungen' into 263
[kivitendo-erp.git] / SL / DB / BackgroundJob.pm
1 package SL::DB::BackgroundJob;
2
3 use strict;
4
5 use DateTime::Event::Cron;
6 use English qw(-no_match_vars);
7
8 use SL::DB::MetaSetup::BackgroundJob;
9 use SL::DB::Manager::BackgroundJob;
10
11 use SL::DB::BackgroundJobHistory;
12
13 use SL::BackgroundJob::Test;
14
15 sub update_next_run_at {
16   my $self = shift;
17
18   my $cron = DateTime::Event::Cron->new_from_cron($self->cron_spec || '* * * * *');
19   $self->update_attributes(next_run_at => $cron->next(DateTime->now_local));
20   return $self;
21 }
22
23 sub run {
24   my $self = shift;
25
26   my $package = "SL::BackgroundJob::" . $self->package_name;
27   my $run_at  = DateTime->now_local;
28   my $history;
29
30   my $ok = eval {
31     my $result = $package->new->run($self);
32
33     $history = SL::DB::BackgroundJobHistory
34       ->new(package_name => $self->package_name,
35             run_at       => $run_at,
36             status       => 'success',
37             result       => $result,
38             data         => $self->data);
39     $history->save;
40
41     1;
42   };
43
44   if (!$ok) {
45     my $error = $EVAL_ERROR;
46     $history = SL::DB::BackgroundJobHistory
47       ->new(package_name => $self->package_name,
48             run_at       => $run_at,
49             status       => 'failure',
50             error_col    => $error,
51             data         => $self->data);
52     $history->save;
53
54     $::lxdebug->message(LXDebug->WARN(), "BackgroundJob ID " . $self->id . " execution error (first three lines): " . join("\n", (split(m/\n/, $error))[0..2]));
55   }
56
57   $self->assign_attributes(last_run_at => $run_at)->update_next_run_at;
58
59   return $history;
60 }
61
62 sub data_as_hash {
63   my $self = shift;
64   return {}                        if !$self->data;
65   return $self->data               if ref($self->{data}) eq 'HASH';
66   return YAML::Load($self->{data}) if !ref($self->{data});
67   return {};
68 }
69
70 1;