Keep running a second function in the background in Go

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

Keep running a second function in the background in Go

问题

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

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

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

英文:

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

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

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来简单实现这一点。就像这样:

  1. package main
  2. import "fmt"
  3. func main() {
  4. //你想要“在后台运行”的函数
  5. go sendTicket(userTickets, firstName, lastName, email)
  6. 其他函数...
  7. }

希望这对你有帮助!

英文:

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

  1. package main
  2. import "fmt"
  3. func main() {
  4. //function you want to "run in background"
  5. go sendTicket(userTickets, firstName, lastName, email)
  6. other functions...
  7. }

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:

确定