Real-World Time Scenarios
Introduction to Practical Time Handling
Real-world applications often require sophisticated time management techniques. This section explores practical scenarios that demonstrate advanced time manipulation in Go.
Logging and Timestamp Management
Structured Logging with Timestamps
package main
import (
"fmt"
"log"
"time"
)
type LogEntry struct {
Timestamp time.Time
Message string
Severity string
}
func createLogEntry(message string, severity string) LogEntry {
return LogEntry{
Timestamp: time.Now(),
Message: message,
Severity: severity,
}
}
func main() {
entry := createLogEntry("System startup", "INFO")
fmt.Printf("Log Entry: %+v\n", entry)
}
Scheduling and Periodic Tasks
Implementing Cron-like Functionality
package main
import (
"fmt"
"time"
)
func periodicTask(interval time.Duration, task func()) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
task()
}
}
}
func main() {
go periodicTask(5*time.Second, func() {
fmt.Println("Periodic task executed at:", time.Now())
})
// Keep main goroutine running
time.Sleep(20 * time.Second)
}
Time-Based Caching Mechanism
package main
import (
"fmt"
"sync"
"time"
)
type CacheItem struct {
Value interface{}
Expiration time.Time
}
type TimeCache struct {
items map[string]CacheItem
mu sync.RWMutex
}
func (c *TimeCache) Set(key string, value interface{}, duration time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = CacheItem{
Value: value,
Expiration: time.Now().Add(duration),
}
}
func (c *TimeCache) Get(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
item, found := c.items[key]
if !found || time.Now().After(item.Expiration) {
return nil, false
}
return item.Value, true
}
Time Scenario Classification
Scenario |
Key Considerations |
Typical Use Case |
Logging |
Precision, Timezone |
System monitoring |
Caching |
Expiration, Concurrency |
Performance optimization |
Scheduling |
Interval, Reliability |
Periodic tasks |
Time Flow in Complex Systems
graph LR
A[Event Trigger] --> B[Timestamp Generation]
B --> C[Time-Based Processing]
C --> D[Caching/Storage]
D --> E[Expiration Check]
package main
import (
"fmt"
"time"
)
func measurePerformance(operation func()) time.Duration {
start := time.Now()
operation()
return time.Since(start)
}
func main() {
duration := measurePerformance(func() {
// Simulate some work
time.Sleep(100 * time.Millisecond)
})
fmt.Printf("Operation took: %v\n", duration)
}
Advanced Time Handling Patterns
- Use context with timeouts
- Implement exponential backoff
- Handle timezone conversions carefully
- Use atomic operations for concurrent time-based logic
Error Handling in Time Operations
package main
import (
"fmt"
"time"
)
func safeTimeParse(timeStr string) (time.Time, error) {
formats := []string{
time.RFC3339,
"2006-01-02 15:04:05",
"2006/01/02",
}
for _, format := range formats {
if parsed, err := time.Parse(format, timeStr); err == nil {
return parsed, nil
}
}
return time.Time{}, fmt.Errorf("unable to parse time")
}
LabEx Learning Tip
Explore these real-world scenarios in LabEx's interactive Go programming environments to gain practical experience with time manipulation techniques.