提供将 Dart 程序作为 Windows Service 在后台长期运行的能力
Github存储库 github.com/au-top/dart…
包含 service_base WindowsServiceDLL dart_windows_service_support 三个部分
service_base github.com/tromgy/serv… 项目提供一个包装了后的 Windows Service API 编译成 lib
WindowsServiceDLL 导入 service_base.lib 并且进一步封装成 对 Dart友好的 C API 后编译到 dll
dart_windows_service_support 使用 dart:ffi 访问 WindowsServiceDLL 中的API 并且封装成 Dart API
示例
示例的全局变量
final dllPath = normalize(join(dirname(Platform.script.toFilePath()),"../../../dll/WindowsServiceDLL.dll"));
const serviceName = "dartTestService";
安装服务 DartConnectServiceDLL.dartInstallService
void main(List<String> args) {
final dartConnectServiceDLL = DartConnectServiceDLL(dllPath);
final servicePath = join(Directory.current.path, "service.exe");
dartConnectServiceDLL.dartInstallService(
serviceName.toNativeUtf16().cast<Uint16>(),
serviceName.toNativeUtf16().cast<Uint16>(),
"this is a dart test service".toNativeUtf16().cast<Uint16>(),
"".toNativeUtf16().cast<Uint16>(),
0x2,
"".toNativeUtf16().cast<Uint16>(),
Pointer.fromAddress(0),
Pointer.fromAddress(0),
/// path
servicePath.toNativeUtf16().cast<Uint16>(),
true,
1,
Pointer.fromAddress(0),
);
}
服务本体 DartConnectServiceDLL.dartConnectService
void main(List<String> args) async {
final dartConnectServiceDLL = DartConnectServiceDLL(dllPath);
await Isolate.spawn(run, 'message');
dartConnectServiceDLL.dartConnectService(serviceName.toNativeUtf16().cast<Uint16>());
}
void run(String message) {
Timer.periodic(Duration(seconds: 1), (timer) async {
final f = File("d:/a.txt");
await f.create();
await f.writeAsString("${await f.readAsString()}1");
});
}
卸载服务 DartConnectServiceDLL.dartUninstallService
void main(List<String> args) {
final dartConnectServiceDLL = DartConnectServiceDLL(dllPath);
dartConnectServiceDLL.dartUninstallService(serviceName.toNativeUtf16().cast<Uint16>());
}