Home  >  Article  >  Database  >  How to develop a simple task scheduling system using MySQL and Go language

How to develop a simple task scheduling system using MySQL and Go language

王林
王林Original
2023-09-21 13:55:521209browse

How to develop a simple task scheduling system using MySQL and Go language

How to use MySQL and Go language to develop a simple task scheduling system

The task scheduling system is a common application scenario, which can help us manage and execute various tasks. types of tasks. This article will introduce how to use MySQL and Go language to develop a simple task scheduling system, and provide specific code examples.

  1. Create database table

First, we need to create a database table to store task information. In MySQL, you can use the following command to create a table named tasks:

CREATE TABLE tasks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(255) NOT NULL,
  schedule_time DATETIME NOT NULL,
  status ENUM('pending', 'running', 'finished', 'failed') NOT NULL DEFAULT 'pending'
);

The table contains the following fields:

  • id: the unique identifier of the task, using an auto-incrementing primary key .
  • name: The name of the task.
  • schedule_time: The planned execution time of the task.
  • status: The execution status of the task, including pending (to be executed), running (executing), finished (execution completed) and failed (execution failed).
  1. Connecting to the database

In the Go language, you can use the database/sql package to connect and operate the database. First, we need to import the relevant packages:

import (
  "database/sql"
  _ "github.com/go-sql-driver/mysql"
)

Then, we can use the following code to connect to the MySQL database:

db, err := sql.Open("mysql", "用户名:密码@tcp(localhost:3306)/数据库名")
if err != nil {
  log.Fatal(err)
}
defer db.Close()
  1. Create a scheduled task

Connect Next, we will use the time package and goroutine in the Go language to create scheduled tasks. First, we need to write a function to perform specific task logic. For example, the following code defines a simple task logic, which outputs the task name and current time:

func taskFunc(name string) {
  fmt.Printf("任务 %s 执行时间:%s
", name, time.Now().Format("2006-01-02 15:04:05"))
}

Then, we can use the following code to create a scheduled task to be executed at the specified time:

func scheduleTask(db *sql.DB, name string, scheduleTime time.Time) {
  // 将任务插入数据库
  _, err := db.Exec("INSERT INTO tasks (name, schedule_time) VALUES (?, ?)", name, scheduleTime)
  if err != nil {
    log.Fatal(err)
  }

  // 进行定时调度
  duration := time.Until(scheduleTime)
  time.AfterFunc(duration, func() {
    // 更新任务状态为running
    _, err := db.Exec("UPDATE tasks SET status = 'running' WHERE name = ? AND schedule_time = ?", name, scheduleTime)
    if err != nil {
      log.Fatal(err)
    }

    // 执行任务
    taskFunc(name)

    // 更新任务状态为finished
    _, err = db.Exec("UPDATE tasks SET status = 'finished' WHERE name = ? AND schedule_time = ?", name, scheduleTime)
    if err != nil {
      log.Fatal(err)
    }
  })
}

In the above code, first insert the task information into the database, then calculate the time difference from the current time to the task execution time, use the time.AfterFunc function to create a timer and execute the task after the specified time logic. Before and after task execution, we also update the status of the task.

  1. Scheduling tasks

Now, we can write a function to schedule multiple tasks. For example, the following code creates two sample tasks and schedules them using the scheduleTask function:

func main() {
  // 连接数据库
  db, err := sql.Open("mysql", "用户名:密码@tcp(localhost:3306)/数据库名")
  if err != nil {
    log.Fatal(err)
  }
  defer db.Close()

  // 调度任务
  scheduleTask(db, "Task 1", time.Now().Add(10*time.Second))
  scheduleTask(db, "Task 2", time.Now().Add(20*time.Second))

  // 等待任务完成
  time.Sleep(30 * time.Second)
}

In the above code, we use time.Now().Add Function to calculate the planned execution time of a task. After scheduling the task, we put the program to sleep for 30 seconds and wait for the task execution to complete.

Summary:
This article introduces how to use MySQL and Go language to develop a simple task scheduling system. By creating database tables, connecting to the database, creating scheduled tasks and scheduling tasks, we can manage and execute different types of tasks. The above is just a simple example, the actual situation may be more complex. However, by referring to the code examples in this article, you can easily extend and customize your own task scheduling system.

The above is the detailed content of How to develop a simple task scheduling system using MySQL and Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn