SoFunction
Updated on 2025-03-06

Go language encapsulates a Cron timing task manager

introduce

In modern applications, timing tasks are a very common requirement, whether it is used to clean data regularly, send emails regularly, or perform system maintenance tasks regularly. As a modern programming language, Go language provides multiple methods to implement timing tasks. This article will focus on how to encapsulate a Cron timing task manager in Go to help developers manage timing tasks efficiently.

Target

We will implement a simple and flexible scheduled task scheduler by using the /robfig/cron/v3 library. This library supports task scheduling based on Cron expressions. We will encapsulate a simple API based on this library for developers to use in actual projects.

Project background

A Cron expression is a format used to represent time plans. It usually consists of 5 or 6 fields that represent a specific point in time or interval. The robfig/cron library in Go provides a very convenient interface to handle these expressions and enables regular tasks.

Our goal is to encapsulate a Crontab structure that will manage all timing tasks, support the addition, deletion, query, and start and stop functions of tasks.

Code Analysis

Below is the encapsulation code for a simple Cron timing task scheduler. It is based on the robfig/cron library and extends a Crontab structure, providing some common operating methods.

Code implementation

package crontab

import (
	"/pkg/errors"
	cron "/robfig/cron/v3"
	"sync"
)

// Crontab crontab struct
type Crontab struct {
	inner *
	ids   map[string]
	mutex *
}

// NewCrontab new crontab
func NewCrontab() *Crontab {
	return &Crontab{
		inner: (()), // Supports second-level Cron expressions		ids:   make(map[string]),
		mutex: new(),
	}
}

// IDs Get all valid Cron task IDsfunc (c *Crontab) IDs() []string {
	()
	defer ()

	validIDs := make([]string, 0, len())
	invalidIDs := make([]string, 0)
	for sid, eid := range  {
		if e := (eid);  != eid {
			invalidIDs = append(invalidIDs, sid)
			continue
		}
		validIDs = append(validIDs, sid)
	}

	// Clean up invalid task ID	for _, id := range invalidIDs {
		delete(, id)
	}

	return validIDs
}

// Start Start the timing task schedulerfunc (c *Crontab) Start() {
	()
}

// Stop Stop the scheduler for timing tasksfunc (c *Crontab) Stop() {
	()
}

// DelByID deletes timing tasks based on IDfunc (c *Crontab) DelByID(id string) error {
	()
	defer ()

	eid, ok := [id]
	if !ok {
		return ("crontab id not exists!")
	}
	(eid)
	delete(, id)

	return nil
}

// AddByID Add timed tasks according to ID// spec is a Cron expression, cmd is the task executedfunc (c *Crontab) AddByID(id, spec string, cmd ) error {
	()
	defer ()

	if _, ok := [id]; ok {
		return ("crontab id exists!")
	}
	eid, err := (spec, cmd)
	if err != nil {
		return err
	}
	[id] = eid
	return nil
}

// AddByFunc adds functions as timing tasks according to IDfunc (c *Crontab) AddByFunc(id, spec string, f func()) error {
	()
	defer ()

	if _, ok := [id]; ok {
		return ("crontab id exists!")
	}
	eid, err := (spec, f)
	if err != nil {
		return err
	}
	[id] = eid
	return nil
}

// IsExists determines whether a task ID already existsfunc (c *Crontab) IsExists(jid string) bool {
	()
	defer ()

	_, exist := [jid]
	return exist
}

Main functions

NewCrontab(): Initializes a new Crontab instance and uses () internally to create a Cron scheduler that supports second-level Cron expressions.

IDs(): Gets all currently valid timing task IDs. The invalid task ID will be cleaned.

Start(): Start the Cron scheduler and start executing all timing tasks.

Stop(): Stops the Cron scheduler and pauses the execution of the timed task.

DelByID(id): Delete the timed task according to the task ID.

AddByID(id, spec, cmd): Add a new timing task according to the Cron expression. The task ID must be unique.

AddByFunc(id, spec, f): Add a function as a timing task and use the Cron expression to specify the execution frequency.

IsExists(jid): determines whether a timing task ID exists.

Cron expression parsing

A Cron expression is a common representation in timed task scheduling. It consists of five or six fields, each representing a unit of time. The standard Cron expression format is as follows:

* * * * * *
│ │ │ │ │ │
│ │ │ │ └─ Day of the week (0 - 7) (0 or 7 represents Sunday)
│ │ │ └────Month (1 - 12)
│ │ └───────Day (1 - 31)
│ │ └───────────Hours (0 - 23)
│ └──────────────── Minutes (0 - 59)
└────────────────────Second (0 - 59)

example

  • * * * * *: Execute tasks once per second
  • 0 * * * * *: Perform a task at the 0th second per minute
  • 0 0 * * * *: Perform tasks once every day at midnight
  • 0 0 1 * * *: Perform tasks once the first day of each month

Example of usage

Here is an example of how to use the encapsulated Crontab type to manage timing tasks:

package main

import (
	"fmt"
	"/robfig/cron/v3"
	"time"
	"your_project/crontab"
)

func main() {
	// Create a new Crontab instance	c := ()

	// Define a timed task	task := func() {
		("Task executed at", ())
	}

	// Add timed tasks	err := ("task1", "*/5 * * * * *", task) // Execute every 5 seconds	if err != nil {
		("Error adding task:", err)
		return
	}

	// Start the task scheduler	()

	// Stop after waiting for a while	(20 * )
	()

	// Delete the task	err = ("task1")
	if err != nil {
		("Error deleting task:", err)
	}
}

Summarize

By using the robfig/cron library and encapsulating it into a simple and easy-to-use Crontab type, we can manage timing tasks very easily in our Go projects. Cron expressions provide us with flexible time configuration to help developers cope with complex timing task scheduling needs.

In practical applications, we can expand the Crontab type as needed, support more functions, such as task status monitoring, task retry, etc., further improving the efficiency of timed task management.

This is the end of this article about encapsulating a Cron timing task manager in Go language. For more information about encapsulating a Cron timing task, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!