Keep running a second function in the background in Go

huangapple go评论68阅读模式
英文:

Keep running a second function in the background in Go

问题

我想在程序执行时保持一个函数在后台运行。

func sendTicket(userTickets uint, firstName string, lastName string, email string) {
    time.Sleep(20 * time.Second) //模拟邮件延迟
    var ticket = fmt.Sprintf("%v张票给%v %v", userTickets, firstName, lastName)
    fmt.Println("\n")
    fmt.Println("*******************************************************")
    fmt.Printf("发送票据:\n %v \n到邮箱地址 %v\n ", ticket, email)
    fmt.Println("*******************************************************")
}

这是我想要在后台持续运行的函数。由于它有20秒的等待时间,我希望这个函数在其他函数运行时打印出消息。

英文:

I want to keep running a Function in the background while the program execute.

func sendTicket(userTickets uint, firstName string, lastName string, email string) {
	time.Sleep(20 * time.Second) //Simulate email delay
	var ticket = fmt.Sprintf("%v tickets for %v %v", userTickets, firstName, lastName)
	fmt.Println("\n")
	fmt.Println("*******************************************************")
	fmt.Printf("Sending Ticket:\n %v \nto email address %v\n ", ticket, email)
	fmt.Println("*******************************************************")
}

This is the function I want to keep running in the background. As it has a 20 second wait time, I want this function print out the message while the other functions are running.

答案1

得分: 2

我认为你在谈论并发。当你调用这个函数时,你可以通过输入go来简单实现这一点。就像这样:

package main

import "fmt"

func main() {        
    //你想要“在后台运行”的函数
    go sendTicket(userTickets, firstName, lastName, email)

    其他函数...
}

希望这对你有帮助!

英文:

I think you are talking about concurrency. You can simply achieve this by typing go when you are calling this function.
Like this,

package main

import "fmt"

func main() {        
    //function you want to "run in background"
    go sendTicket(userTickets, firstName, lastName, email)

    other functions...

}

huangapple
  • 本文由 发表于 2022年2月18日 00:55:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/71162275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定