github.com/matrixorigin/matrixone@v1.2.0/pkg/taskservice/cron_state.go (about) 1 // Copyright 2024 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package taskservice 16 17 import "sync" 18 19 // cronServiceState protect that: 20 // 1. cannot start when started. 21 // 2. cannot start when stopping. 22 // 3. can start after endStop. 23 // 4. cannot stop when stopping. 24 // 5. cannot stop after endStop. 25 // 6. cannot stop when not started. 26 // 7. can stop when started. 27 type cronServiceState struct { 28 sync.Mutex 29 started bool 30 stopping bool 31 } 32 33 func (s *cronServiceState) canStart() bool { 34 s.Lock() 35 defer s.Unlock() 36 if s.stopping || s.started { 37 return false 38 } 39 s.started = true 40 return true 41 } 42 43 func (s *cronServiceState) canStop() bool { 44 s.Lock() 45 defer s.Unlock() 46 if !s.started || s.stopping { 47 return false 48 } 49 s.stopping = true 50 return true 51 } 52 53 func (s *cronServiceState) endStop() { 54 s.Lock() 55 defer s.Unlock() 56 s.started = false 57 s.stopping = false 58 } 59 60 // cronJobState protect that: 61 // 1. cannot run when updating. 62 // 2. cannot run when running. 63 // 3. cannot update when running. 64 // 4. can update when not running. 65 // 5. can run when not updating. 66 type cronJobState struct { 67 sync.Mutex 68 running bool 69 updating bool 70 } 71 72 func (s *cronJobState) canRun() bool { 73 s.Lock() 74 defer s.Unlock() 75 if s.updating || s.running { 76 return false 77 } 78 s.running = true 79 return true 80 } 81 82 func (s *cronJobState) endRun() { 83 s.Lock() 84 defer s.Unlock() 85 s.running = false 86 s.updating = false 87 } 88 89 func (s *cronJobState) canUpdate() bool { 90 s.Lock() 91 defer s.Unlock() 92 if s.running { 93 return false 94 } 95 s.updating = true 96 return true 97 } 98 99 func (s *cronJobState) endUpdate() { 100 s.Lock() 101 defer s.Unlock() 102 s.running = false 103 s.updating = false 104 }