github.com/matrixorigin/matrixone@v1.2.0/pkg/vm/engine/tae/gc/job.go (about)

     1  // Copyright 2021 Matrix Origin
     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 gc
    16  
    17  import (
    18  	"bytes"
    19  	"context"
    20  	"fmt"
    21  	"time"
    22  )
    23  
    24  type Job = func(context.Context) error
    25  
    26  type cronJob struct {
    27  	// cron job name
    28  	name string
    29  
    30  	// cron job interval
    31  	interval time.Duration
    32  
    33  	// previous run time
    34  	prev time.Time
    35  	// next run time
    36  	next time.Time
    37  
    38  	// the underlying job
    39  	job Job
    40  }
    41  
    42  func (cj *cronJob) init(t time.Time) {
    43  	cj.next = t
    44  }
    45  
    46  func (cj *cronJob) reschedule(t time.Time) {
    47  	cj.prev = cj.next
    48  	cj.next = t.Add(cj.interval)
    49  }
    50  
    51  func (cj *cronJob) after(t time.Time) bool {
    52  	return cj.next.After(t)
    53  }
    54  
    55  func (cj *cronJob) String() string {
    56  	return fmt.Sprintf("job=%s, inv=%s",
    57  		cj.name, cj.interval)
    58  	// return fmt.Sprintf("job=%s, inv=%s, prev=%s, next=%s\n",
    59  	// 	cj.name, cj.interval, cj.prev, cj.next)
    60  }
    61  
    62  type cronJobs []*cronJob
    63  
    64  func (jobs cronJobs) Len() int      { return len(jobs) }
    65  func (jobs cronJobs) Swap(i, j int) { jobs[i], jobs[j] = jobs[j], jobs[i] }
    66  func (jobs cronJobs) Less(i, j int) bool {
    67  	return jobs[i].next.Before(jobs[j].next)
    68  }
    69  
    70  func (jobs cronJobs) String() string {
    71  	w := new(bytes.Buffer)
    72  	for i, job := range jobs {
    73  		_, _ = w.WriteString(fmt.Sprintf("%d. %s\n", i+1, job.String()))
    74  	}
    75  	return w.String()
    76  }