@@ -2,20 +2,38 @@ require_relative '../statistics.rb'
2
2
3
3
namespace :statistics do
4
4
desc '月次のイベント履歴を集計します'
5
- task :aggregation , [ :from_yyyymm , :to_yyyymm ] => :environment do |tasks , args |
5
+ task :aggregation , [ :from , :to ] => :environment do |tasks , args |
6
6
date_from_str = -> ( str ) {
7
- d = %w( %Y%m %Y/%m %Y-%m ) . map { |fmt |
7
+ formats = %w( %Y%m %Y/%m %Y-%m )
8
+ d = formats . map { |fmt |
8
9
begin
9
10
Time . zone . strptime ( str , fmt )
10
11
rescue ArgumentError
12
+ Time . zone . local ( str ) if str . length == 4
11
13
end
12
14
} . compact . first
13
- raise ArgumentError , "Invalid format: `#{ str } `" if d . nil?
15
+ raise ArgumentError , "Invalid format: `#{ str } `, allow format is #{ formats . push ( '%Y' ) . join ( ' or ' ) } " if d . nil?
14
16
d
15
17
}
16
18
17
- from = ( args [ :from_yyyymm ] ? date_from_str . call ( args [ :from_yyyymm ] ) : Time . current . prev_month ) . beginning_of_month
18
- to = ( args [ :to_yyyymm ] ? date_from_str . call ( args [ :to_yyyymm ] ) : Time . current . prev_month ) . end_of_month
19
+ from = if args [ :from ]
20
+ if args [ :from ] . length == 4
21
+ date_from_str . call ( args [ :from ] ) . beginning_of_year
22
+ else
23
+ date_from_str . call ( args [ :from ] ) . beginning_of_month
24
+ end
25
+ else
26
+ Time . current . prev_month . beginning_of_month
27
+ end
28
+ to = if args [ :to ]
29
+ if args [ :to ] . length == 4
30
+ date_from_str . call ( args [ :to ] ) . end_of_year
31
+ else
32
+ date_from_str . call ( args [ :to ] ) . end_of_month
33
+ end
34
+ else
35
+ Time . current . prev_month . end_of_month
36
+ end
19
37
20
38
EventHistory . where ( evented_at : from ..to ) . delete_all
21
39
@@ -24,7 +42,15 @@ namespace :statistics do
24
42
raise StopIteration if nm > to
25
43
list << nm
26
44
} . each { |date |
27
- Statistics ::Aggregation . run ( date : date )
45
+ begin
46
+ puts "Aggregate for #{ date . strftime ( '%Y/%m' ) } "
47
+ Statistics ::Aggregation . run ( date : date )
48
+ rescue Statistics ::Client ::APIRateLimitError
49
+ puts 'API rate limit exceeded.'
50
+ puts "This task will retry in 60 seconds from now(#{ Time . zone . now } )."
51
+ sleep 60
52
+ retry
53
+ end
28
54
}
29
55
end
30
56
0 commit comments