delog.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "fmt"
  4. cron "github.com/robfig/cron/v3"
  5. "io/ioutil"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. )
  10. // 删除子目录下的以.html结尾的文件,创建时间早于keepDate的保留
  11. func deleteHTMLFiles(dirPath string, keepDate time.Time) {
  12. files, err := ioutil.ReadDir(dirPath)
  13. if err != nil {
  14. fmt.Printf("Error reading directory %s: %v\n", dirPath, err)
  15. return
  16. }
  17. for _, file := range files {
  18. if !file.IsDir() && filepath.Ext(file.Name()) == ".html" {
  19. filePath := filepath.Join(dirPath, file.Name())
  20. if file.ModTime().Before(keepDate) {
  21. err := os.Remove(filePath)
  22. if err != nil {
  23. fmt.Printf("Error deleting file %s: %v\n", filePath, err)
  24. } else {
  25. fmt.Printf("Deleted file: %s\n", filePath)
  26. }
  27. } else {
  28. fmt.Printf("File %s is within the keep period. Skipping deletion.\n", filePath)
  29. }
  30. }
  31. }
  32. }
  33. func start() {
  34. // 获取当前目录的绝对路径
  35. currentDir, err := os.Getwd()
  36. if err != nil {
  37. fmt.Println("Error getting current directory:", err)
  38. os.Exit(1)
  39. }
  40. // 获取当前日期和保留日期(前三天)
  41. currentTime := time.Now()
  42. keepDate := currentTime.AddDate(0, 0, -3)
  43. // 遍历当前目录的子目录
  44. subDirs, err := ioutil.ReadDir(currentDir)
  45. if err != nil {
  46. fmt.Println("Error reading current directory:", err)
  47. os.Exit(1)
  48. }
  49. // 删除子目录下的以.html结尾的文件
  50. for _, subDir := range subDirs {
  51. if subDir.IsDir() {
  52. subDirPath := filepath.Join(currentDir, subDir.Name())
  53. deleteHTMLFiles(subDirPath, keepDate)
  54. }
  55. }
  56. fmt.Println("Deletion of .html files completed.")
  57. }
  58. func main() {
  59. // 获取当前目录的绝对路径
  60. currentDir, _ := os.Getwd()
  61. fmt.Print("currentDir=",currentDir,"\n")
  62. c := cron.New()
  63. i := 1
  64. _, _ = c.AddFunc("0 0 */1 * *", func() {
  65. start()
  66. line := "\n--------------------------------------------------------\n"
  67. fmt.Println(line, time.Now(), line)
  68. i++
  69. })
  70. c.Run()
  71. }