task.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/robfig/cron"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os/exec"
  9. "time"
  10. )
  11. func TimeTask() {
  12. c := cron.New()
  13. cronstr := "@every " + fmt.Sprint(config.TaskTime) + "m"
  14. _ = c.AddFunc(cronstr, func() {
  15. log.Println("每3分钟执行一次")
  16. StartTask()
  17. })
  18. c.Start()
  19. }
  20. func StartTask() {
  21. time.AfterFunc(time.Second * time.Duration(config.AdvanceTime), DestroyRes)
  22. registe()
  23. }
  24. func DestroyRes() {
  25. log.Println("提前销毁资源")
  26. destory()
  27. }
  28. //公网IP
  29. func getMyIp() string {
  30. resp, err := http.Get("http://myexternalip.com/raw")
  31. if err != nil {
  32. return ""
  33. }
  34. defer resp.Body.Close()
  35. bs, _ := ioutil.ReadAll(resp.Body)
  36. ip := myipreg.FindString(string(bs))
  37. return ip
  38. }
  39. //切换ip, 保证与旧IP不重复
  40. func changeIP() {
  41. for i := 0; i < 10; i++ {
  42. exec.Command("rasdial", config.Name, "/disconnect").Run()
  43. exec.Command("rasdial", config.Name, config.User, config.Pwd).Run()
  44. ////清空
  45. //for k, _ := range cache {
  46. // delete(cache, k)
  47. //}
  48. newip := getMyIp()
  49. if newip == "" {
  50. log.Println("取不到公网IP,可能拨号失败了")
  51. time.Sleep(1 * time.Minute)
  52. } else if myoldip != newip {
  53. log.Printf("你的公网IP从%s换成%s \n", myoldip, newip)
  54. myoldip = newip
  55. break
  56. } else {
  57. log.Println("取到的IP重复了")
  58. }
  59. }
  60. }