Debian Codegraph @

schedule/schedule.go

raw
1 // Copyright 2019 Google LLC. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package schedule provides support for periodically running a function.
16 package schedule
17
18 import (
19 "context"
20 "time"
21 )
22
23 // Every will call f periodically.
24 // The first call will be made immediately.
25 // Calls are made synchronously, so f will not be executed concurrently.
26 func Every(ctx context.Context, period time.Duration, f func(context.Context)) {
27 if ctx.Err() != nil {
28 return
29 }
30 // Run f immediately, then periodically call it again.
31 t := time.NewTicker(period)
32 defer t.Stop()
33 f(ctx)
34 for {
35 select {
36 case <-t.C:
37 f(ctx)
38 case <-ctx.Done():
39 return
40 }
41 }
42 }