0
点赞
收藏
分享

微信扫一扫

示例 20: Go语言实现任务调度系统

需求:

实现一个简单的任务调度系统,定时执行任务并记录日志。

代码:

package main

import (
	"fmt"
	"log"
	"time"
)

// Task represents a task to be scheduled
type Task struct {
	ID   int
	Name string
}

// Execute runs the task and logs the execution time
func (t Task) Execute() {
	fmt.Printf("Executing task: %d - %s at %s\n", t.ID, t.Name, time.Now().Format(time.RFC3339))
}

// Scheduler manages task scheduling
type Scheduler struct {
	tasks []Task
}

// AddTask adds a task to the scheduler
func (s *Scheduler) AddTask(task Task) {
	s.tasks = append(s.tasks, task)
}

// Start starts the scheduler to execute tasks at regular intervals
func (s *Scheduler) Start() {
	for _, task := range s.tasks {
		go func(t Task) {
			for {
				time.Sleep(5 * time.Second) // Schedule every 5 seconds
				t.Execute()
			}
		}(task)
	}
}

func main() {
	scheduler := &Scheduler{}
	task1 := Task{ID: 1, Name: "Task 1"}
	task2 := Task{ID: 2, Name: "Task 2"}

	scheduler.AddTask(task1)
	scheduler.AddTask(task2)

	// Start the scheduler
	scheduler.Start()

	// Block forever to keep the scheduler running
	select {}
}

解释:

  • 创建了一个简单的任务调度器Scheduler,它可以定时执行任务。
  • 每个任务每5秒执行一次,输出执行时间。
  • 使用go关键字来并发执行每个任务。

扩展:

  • 增加任务的优先级。
  • 可以使用一个队列来管理任务,并实现任务的定时启动或延迟执行。
举报

相关推荐

0 条评论