Python.NETを使用しているときに時間がかかりすぎるときは、変換または読み込みをInterruptMonitorで停止します。

可能な使用シナリオ

Aspose.Cellsは、変換に時間がかかりすぎる場合、WorkbookをPDFやHTMLなどさまざまな形式に変換する際にInterruptMonitorオブジェクトを使って停止できます。変換処理はCPUとメモリの両方に負荷をかけることが多く、リソースが限られている場合に停止するのが有効です。InterruptMonitorは変換停止だけでなく、大きなワークブックの読み込み停止にも利用できます。変換停止にはWorkbook.interrupt_monitorプロパティを、読み込み停止にはLoadOptions.interrupt_monitorプロパティを使用してください。

時間がかかりすぎる場合はInterruptMonitorを使用して変換または読み込みを停止してください

次のサンプルコードでは、InterruptMonitorオブジェクトの使用方法について説明しています。多大なExcelファイルをPDFに変換します。このコードは、これらのコードの行のために変換が数秒かかります(すなわち30秒以上)。

# Access cell J1000000 and add some text inside it.
cell = ws.cells.get("J1000000")
cell.put_value("This is text.")

ご覧のとおり、J1000000はXLSXファイルのかなり遠いセルです。ただし、**wait_for_while_and_then_interrupt()**メソッドは10秒後に変換を中断し、プログラムを終了します。サンプルコードを実行するには、次のコードを使用してください。

StopConversionOrLoadingUsingInterruptMonitor().test_run()

サンプルコード

import os
import threading
import time
from aspose.cells import Workbook, Worksheet, CellsException, ExceptionType
from aspose.cells import InterruptMonitor

class StopConversionOrLoadingUsingInterruptMonitor:
    # Output directory
    output_dir = None  # Will be set using GetOutputDirectory()

    def __init__(self):
        # Create InterruptMonitor object
        self.im = InterruptMonitor()
        self.output_dir = self.get_output_directory()

    @staticmethod
    def get_output_directory():
        current_dir = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(current_dir, "output")

    def create_workbook_and_convert_to_pdf(self, monitor_thread):
        # Create a workbook object
        wb = Workbook()
        # Assign InterruptMonitor object
        wb.interrupt_monitor = self.im

        # Access first worksheet
        ws = wb.worksheets[0]

        # Access cell J1000000 and add text
        cell = ws.cells.get("J1000000")
        cell.put_value("This is text.")

        try:
            # Save to PDF
            output_path = os.path.join(self.output_dir, "output_InterruptMonitor.pdf")
            wb.save(output_path)
            print("Excel to PDF - Successful Conversion")
            # Interrupt monitor thread
            monitor_thread.interrupt()
        except CellsException as ex:
            if ex.code == ExceptionType.INTERRUPTED:
                print(f"Conversion process interrupted - Message: {ex.message}")
            else:
                raise

    def wait_and_interrupt(self):
        try:
            time.sleep(10)
            self.im.interrupt()
        except KeyboardInterrupt as e:
            print(f"Monitor thread interrupted - Message: {e}")

    def test_run(self):
        monitor_thread = threading.Thread(target=self.wait_and_interrupt)
        conversion_thread = threading.Thread(
            target=self.create_workbook_and_convert_to_pdf,
            args=(monitor_thread,)
        )

        monitor_thread.start()
        conversion_thread.start()

        monitor_thread.join()
        conversion_thread.join()

    @classmethod
    def run(cls):
        converter = cls()
        converter.test_run()
        print("StopConversionOrLoadingUsingInterruptMonitor executed successfully.")