github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/model/scheduled_task.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"fmt"
     8  	"time"
     9  )
    10  
    11  type TaskFunc func()
    12  
    13  type ScheduledTask struct {
    14  	Name      string        `json:"name"`
    15  	Interval  time.Duration `json:"interval"`
    16  	Recurring bool          `json:"recurring"`
    17  	function  func()
    18  	cancel    chan struct{}
    19  	cancelled chan struct{}
    20  }
    21  
    22  func CreateTask(name string, function TaskFunc, timeToExecution time.Duration) *ScheduledTask {
    23  	return createTask(name, function, timeToExecution, false)
    24  }
    25  
    26  func CreateRecurringTask(name string, function TaskFunc, interval time.Duration) *ScheduledTask {
    27  	return createTask(name, function, interval, true)
    28  }
    29  
    30  func createTask(name string, function TaskFunc, interval time.Duration, recurring bool) *ScheduledTask {
    31  	task := &ScheduledTask{
    32  		Name:      name,
    33  		Interval:  interval,
    34  		Recurring: recurring,
    35  		function:  function,
    36  		cancel:    make(chan struct{}),
    37  		cancelled: make(chan struct{}),
    38  	}
    39  
    40  	go func() {
    41  		defer close(task.cancelled)
    42  
    43  		ticker := time.NewTicker(interval)
    44  		defer func() {
    45  			ticker.Stop()
    46  		}()
    47  
    48  		for {
    49  			select {
    50  			case <-ticker.C:
    51  				function()
    52  			case <-task.cancel:
    53  				return
    54  			}
    55  
    56  			if !task.Recurring {
    57  				break
    58  			}
    59  		}
    60  	}()
    61  
    62  	return task
    63  }
    64  
    65  func (task *ScheduledTask) Cancel() {
    66  	close(task.cancel)
    67  	<-task.cancelled
    68  }
    69  
    70  func (task *ScheduledTask) String() string {
    71  	return fmt.Sprintf(
    72  		"%s\nInterval: %s\nRecurring: %t\n",
    73  		task.Name,
    74  		task.Interval.String(),
    75  		task.Recurring,
    76  	)
    77  }