Run starts the cron scheduler. It is a blocking call.
(ctx context.Context)
| 112 | |
| 113 | // Run starts the cron scheduler. It is a blocking call. |
| 114 | func (c *Cron) Run(ctx context.Context) error { |
| 115 | defer c.quitWaiter.Wait() |
| 116 | |
| 117 | c.lock.L.Lock() |
| 118 | now := c.now() |
| 119 | for _, descriptor := range c.jobDescriptors { |
| 120 | descriptor.next = descriptor.Schedule.Next(now) |
| 121 | } |
| 122 | heap.Init(&c.jobDescriptors) |
| 123 | c.lock.L.Unlock() |
| 124 | |
| 125 | var once sync.Once |
| 126 | for { |
| 127 | c.lock.L.Lock() |
| 128 | // Determine the next entry to run. |
| 129 | for c.jobDescriptors.Len() == 0 || c.jobDescriptors[0].next.IsZero() { |
| 130 | c.broadcastAtDeadlineOnce(ctx, &once) |
| 131 | select { |
| 132 | case <-ctx.Done(): |
| 133 | c.lock.L.Unlock() |
| 134 | return ctx.Err() |
| 135 | default: |
| 136 | c.lock.Wait() |
| 137 | } |
| 138 | } |
| 139 | gap := c.jobDescriptors[0].next.Sub(now) |
| 140 | c.lock.L.Unlock() |
| 141 | |
| 142 | timer := time.NewTimer(gap) |
| 143 | |
| 144 | select { |
| 145 | case now = <-timer.C: |
| 146 | c.lock.L.Lock() |
| 147 | for { |
| 148 | if c.jobDescriptors[0].next.After(now) || c.jobDescriptors[0].next.IsZero() { |
| 149 | break |
| 150 | } |
| 151 | descriptor := heap.Pop(&c.jobDescriptors).(*JobDescriptor) |
| 152 | |
| 153 | descriptor.prev = descriptor.next |
| 154 | descriptor.next = descriptor.Schedule.Next(now) |
| 155 | heap.Push(&c.jobDescriptors, descriptor) |
| 156 | |
| 157 | var innerCtx context.Context |
| 158 | innerCtx = context.WithValue(ctx, prevContextKey, descriptor.prev) |
| 159 | innerCtx = context.WithValue(innerCtx, nextContextKey, descriptor.next) |
| 160 | |
| 161 | c.quitWaiter.Add(1) |
| 162 | go func() { |
| 163 | defer c.quitWaiter.Done() |
| 164 | descriptor.Run(innerCtx) |
| 165 | }() |
| 166 | } |
| 167 | c.lock.L.Unlock() |
| 168 | case <-ctx.Done(): |
| 169 | timer.Stop() |
| 170 | return ctx.Err() |
| 171 | } |