英文:
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...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论