iWatch application got killed

Hi

I am pretty new to ios development and I am trying to write a code to store the acceleration and gyro data into files using iwatch se (OS 7.5), iPhone XSMax (14.7.1) and XCode 12.5.1. I wrote most of my application in the ExtensionDelegate which I put below. The application gets killed after a couple of hours. Any ideas why? I think the watchdog kills it. I know this is not the most efficient way to write it but I was unable to make the timer thing working in the background! :(

import WatchKit
import CoreMotion


class ExtensionDelegate: NSObject, WKExtensionDelegate {
  let motionManagerDelegate = CMMotionManager()
  var sensorDataDelegate=[Double]()
  var offsetTime=0.0
  var offsetTimeFlag=true
   
  func applicationDidFinishLaunching() {
    print("Delegate:App finished lunching")
    self.startQueuedMotionUpdates()
  }

  func applicationDidBecomeActive() {
    print("Delegate:App active")
//    self.startQueuedMotionUpdates()
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
  }

  func applicationWillResignActive() {
    print("Delegate:App will be active")
//    self.startQueuedMotionUpdates()
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, etc.
  }
   
  func applicationDidEnterBackground() {
    print("Delegate:App is background")
//    self.startQueuedMotionUpdates()
    self.binaryWriter()
  }
   
  func applicationWillEnterForeground() {
    print("Delegate:App will be foreground")
//    self.startQueuedMotionUpdates()
  }
   
   
  func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
    self.startQueuedMotionUpdates()
    self.binaryWriter()
    for task in backgroundTasks {
      // Use a switch statement to check the task type

      switch task {
        case let backgroundTask as WKApplicationRefreshBackgroundTask:
          // Be sure to complete the background task once you’re done.
          backgroundTask.setTaskCompletedWithSnapshot(false)
        case let snapshotTask as WKSnapshotRefreshBackgroundTask:
          // Snapshot tasks have a unique completion call, make sure to set your expiration date
          snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
        case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
          // Be sure to complete the connectivity task once you’re done.
          connectivityTask.setTaskCompletedWithSnapshot(false)
        case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
          // Be sure to complete the URL session task once you’re done.
          urlSessionTask.setTaskCompletedWithSnapshot(false)
        case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
          // Be sure to complete the relevant-shortcut task once you're done.
          relevantShortcutTask.setTaskCompletedWithSnapshot(false)
        case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
          // Be sure to complete the intent-did-run task once you're done.
          intentDidRunTask.setTaskCompletedWithSnapshot(false)
        default:
          // make sure to complete unhandled task types
          task.setTaskCompletedWithSnapshot(false)
      }
    }
  }
  func startQueuedMotionUpdates() {
    var myDate = Date()
    var dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd-HH:mm:ss"
    var currentTime = dateFormatter.string(from: myDate)
     
     
    print("sensor function starts==============================",currentTime)
     
    if self.motionManagerDelegate.isDeviceMotionAvailable {
      if !self.motionManagerDelegate.isDeviceMotionActive{
        self.motionManagerDelegate.deviceMotionUpdateInterval = 30 / 60.0
        self.motionManagerDelegate.showsDeviceMovementDisplay = true
      }
        self.motionManagerDelegate.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: OperationQueue.current!, withHandler: { (data, error) in
          if let validData = data {
            let rX = validData.rotationRate.x
            let rY = validData.rotationRate.y
            let rZ = validData.rotationRate.z
            let timeStamp=validData.timestamp
            if self.offsetTimeFlag{
//              let currentTime=Date().timeIntervalSince1970
//              self.offsetTime=currentTime-timeStamp
              self.offsetTime = 0.0-timeStamp
              self.offsetTimeFlag=false
            }
            self.sensorDataDelegate.append(contentsOf: [timeStamp+self.offsetTime])
          }
        })
    }
    else {
      fatalError("The motion data is not avaialable")
    }
    myDate = Date()
    currentTime = dateFormatter.string(from: myDate)
    print("sensor function ends==============================",currentTime)
  }
   
  func binaryWriter() {
    var tempVal = self.sensorDataDelegate
    var myDate = Date()
    var dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM-dd-HH:mm:ss"
    var fileName = dateFormatter.string(from: myDate)
     
    print("Writing Start========================",fileName)
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
      let fileURL = dir.appendingPathComponent(fileName)
      do {
        try (tempVal as NSArray).write(to: fileURL,atomically: true)
      }
      catch {/* error handling here */}
    }
     
    myDate = Date()
    var currentTime = dateFormatter.string(from: myDate)
    print("Writing End========================",currentTime)
    self.sensorDataDelegate.removeAll()
    myDate = Date()
    currentTime = dateFormatter.string(from: myDate)
    print("Data is cleaned========================",currentTime)
  }
   


}